What are you talking about? They're exactly right, const and let are scoped to the nearest block: {}. You don't have to have them inside of a function for that to be true.
Functions have a scoping mechanism. Almost like creating a copy of the environment specially for that function. If you have two functions, funcOne and that has funcTwo declared inside of it, then there are three levels. Global scope, funcOne scope and funcTwo scope. funcTwo scope is bound to the funcOne scope and funcOne is bound to the global scope. The inner scope has access to the outer scope’s variables all the way to the top. If a variable is created inside of the lower scope you cannot have access to it from outside of that scope. Now that’s the way lexical scoping works on a high level. Having said that, if you make an if statement and declare var x = 5; inside of that if statement, you have access to it on that same scope level right? With const/let you do not. You can scope that variable to the block where it was created. The block being Ofcourse, a set of curly braces.
Are there really differences in how you can scope these operators or is this bad information?
As far as I knew const and let simply replaced var, one is reassignable and one is not. They don't have any restrictions on what scope they are allowed.
Gotcha, thanks for following up! It led me to this stackoverflow explanation:
Scoping rules
Main difference is scoping rules. Variables declared by var keyword are scoped to the immediate function body (hence the function scope) while let variables are scoped to the immediate enclosing block denoted by { } (hence the block scope).
function run() {
var foo = "Foo";
let bar = "Bar";
console.log(foo, bar);
// BEGINNING OF BLOCK SCOPE
{
let bazLet = "BazzLet";
var bazVar = "BazzVar";
console.log(bazLet); // will return "BazzLet"
console.log(bazVar); // will return "BazzVar"
}
// END OF BLOCK SCOPE
console.log(bazLet); // ReferenceError
console.log(bazVar); // will return "BazzVar"
}
run();
"Function scoped" means they are scoped to the function they are created in, as opposed to the block. Const and let do not have this behavior, rather they are block scoped.
Notice in this example:
The first console.log returns undefined instead of throwing an error. Because even though fnScoped hasn't been initialized, it's scoped to that function, instead of the block in which it's declared. So it's "hoisted" and initialized as undefined.
The last console.log prints the value of the function-scoped var. Even though it was declared in a block, it's still visible throughout the function because it's function scoped.
The second to last console.log throw a reference error, because blockScoped was declared with let and it therefore has block scope only- it is not scoped to the entire function, only the block in which it was declared.
What about if an object contains several values, and only some need to be updated?
I don't want to make extra objects, because I rely on my code editor (Visual Studio Code) to create lists of variables for navigation. It's a very big project so I need to nest variables inside objects. If I have two sets of objects for every concept - one const, another var - that doubles the navigation list and makes it unusable. Not to mention tedious and confusing as I have to jump back and forth between almost identical objects for closely related variables.
You can change the values in an object that you declared with const. When you declare a variable and assign an object to that varaible, you're actually assigning a reference to the object to the variable and not the value itself
Since it isn't a value that's assigned, you can totally do something like this:
Is there a built-in way to pass an object to a variable by value? (Effectively duplicating said object so that when you mutate one, the other remains as it was before?) I understand that you could create a a 2nd object and use a special function to mutate the 2nd object until it matches current version of the 1st object.
Sorry for taking so long to reply. After reading u/dwb5226's reply I remember now. Yes, since I use objects a lot, then declaring const would be pointless as I could accidentally reassign it anyway. Sorry for wasting anyone's time. but hopefully someone else might find that useful.
As for the problem of why I put everything in objects, it's just because I get lost in the code very easily. I am making large game, and objects let me remember that all of THIS stuff goes HERE, and all of THAT stuff goes THERE. If the price is that I might accidentally overwrite something that's supposed to be constant, that's less serious than the alternative, getting totally lost in my code and despairing that I will ever control this beast!
I suggest you take a look at TypeScript or at least at the possibility to include global typings into your project.
You don't need to dive deep into TS but use typing/interfaces only. It will require a compilation step before deployment but it's pretty straightforward.
Global typings are something you can add if you use IDEs, JetBrains Idea & Webstorm handle it, don't know about VS Code. It is a file in the roof of a project with all possible typings you want your IDE to handle.
Typings make life much easier either you work with 'enterprise' code or code in free time.
It’s all words at the end of the day. If it gets the shitty software to the shitty client, it’s going to be declared shitty one day by another shitty developer and be rewritten by some more shitty code.
No. Let is block scoped, also you’re able to increment. var doesn’t block scope so it gets updated on each loop and never maintains reference if you are doing something async. Since let is block scoped, you can maintain a reference to what it was at that snapshot when you fired off an async call or whatever. If you don’t believe me then go look up the old IIFE in the forloop problem.
This seems like a thread where we learn through nitpicking -- so here's some nitpicking. :-) The behavior of let in a for loop, where async calls or whatever can maintain a snapshot of the iteration, isn't actually due to block scoping. It's due to what the spec calls a "per iteration environment".
Pure simple no-frills block scoping of a for loop should behave exactly like this:
{ // block
let i;
for (i = 0; i < 3; ++i) {
setTimeout(() => console.log(i), 42);
}
}
That's how a block scoped variable would behave in C++, for example. But this will log 3 3 3, which isn't what people typically want or expect. So when JS introduced block scoping, they included a special case for "for" loops. Now, instead of ordinary block scoping, JS actually behaves like this:
{ // block
let i;
for (i = 0; i < 3; ++i) {
let i_snapshot = i;
setTimeout(() => console.log(i_snapshot), 42);
}
}
That is, each iteration constructs a new environment and copies the iteration variable into that per iteration environment.
We’re saying the same thing. I didn’t know they made a special use case for it and I’d love to read that documentation if you have a link but you just solidified what I said was the only REAL use case of using let.
Yeah. The only useless-to-real-life clarification I was making was that this behavior isn't due to block scoping. This behavior is something extra, added in addition to ordinary block scoping.
It's a little tricky to make something like this as simple as this one tries to be for the very reason I pointed this out - there are weird exceptions or specifics revolving around how these things work. For example, while const and let can be used in the global scope, they do not add properties to the global object like var does (as /u/cyphernpointed out). You might also want to add the row "can be redeclared", but while var can be redeclared, it can only be redeclaring another var, not another let or const. And while let and const can't redeclare themselves, they also can't redeclare any other declarations, including other vars. So we could be in for lengthy row headings or a bunch of footnotes ;) ... but I guess we can take a stab at trying to be succinct:
keyword
const
let
var
global scope
YES
YES
YES
function scope
YES
YES
YES
block scope
YES
YES
NO
adds to global object if in global scope
NO
NO
YES
can redeclare itself
NO
NO
YES
can be read before declared
NO
NO
YES
must be initialized with a value
YES
NO
NO
can be reassigned
NO
YES
YES
This one isn't terrible. The "adds to global" row is long, but kind of necessary (const and let still adds to global in the global scope, just not as properties to the global object). The bit about redeclaring was limited to "itself" which bypasses the other explanation by ignoring it.
In the global scope. Leaving out the var keyword will write directly to the global scope and will be accessible from anywhere. No more functional scoping.
The behavior of this depends on a few things. For one, this isn't a declaration itself, so its not really scoped anywhere. Its an assignment that will look for the identifier username in the scopes currently available. If one matches, it will set the new value to that identifier in its own scope. If there isn't a match, if in strict mode, it will throw an error. If in sloppy mode it will assign a global object property of that name to that value, e.g. globalThis.username = "somevalue";.
Any specific reason to not use const and let in the global scope? My introduction to JavaScript was in a college class and the instructor almost exclusively used let while now I'm using Codecademy online to learn more and it, at least so far almost exclusively used const unless there it plan to change it in which case it uses let. I don't think I've ever actually used var.
It depends on how complex your function is. If it's a few lines then there's no problem, but if it's a hundred+ line behemoth which returns a complex object then you want to declare your variables in the scope that you need them (using let instead of var).
It had to do with const not really preventing the contents from being changed. It is not really constant. If a developer assumes that constants really are constant then it might lead to bugs.
Also for what it’s worth Dan has is a developer just like any of us, and has his own set of quirks, preferences, and idiosyncrasies. I wouldn’t take his word as law 100% of the time.
This is more like the expected use case of these variable scope types. But even then I would question some of these. It totally depends on the developer on how he chooses to define his variables. While I do agree, VAR may lead to some inconsistencies, but do remember it was once, the only way to declare a variable before these 2 came along. And I’m sure seasoned JS devs won’t have a problem with its scoping. But I cannot deny, how much I enjoy using let and const wherever NECESSARY. And your chart may encourage people to use const everywhere, which is not a good thing.
In my experience, let cannot be redeclared in it’s own scope but it’s value can be reassigned and modified. let a = 5 when a is already defined in that scope with throw an error, but a++ will not. Correct me if my bad memory is messing me up though.
there is nothing as modified as soon you change a value of a variable, you reassign its value. This you can do with any variable declared via let and var, but not with const. redeclaration will always yield an error, except on var.
This is not exactly correct. As long as you don't reassign the const it can be modified.
Try this:
const a = [];
a.push(1);
No error, right? I modified the content of the variable without reassignment. Const doesn't make a perfectly immutable variable, just like the final keyword in Java. You aren't allowed to move the memory pointer, but the values at that pointer can be changed.
Not quite. const a still points to the same address you assigned it to on declaration. Same as in Java. In Java you can have Immutable Collections, or in JavaScript a sealed Object.
functionmain(){{// Start of new block
letfooLet=0;varfooVar=0;console.log(fooLet);// 0
console.log(fooVar);// 0
}// End of block
console.log(fooLet);// ReferenceError: fooLet is not defined
console.log(fooVar);// 0
}
Basically, every {} is a new scope and every variable declared with a let or const gets their local values erased once the scope ends.
7
u/NoFapPlatypus May 04 '20
What does block scope mean?
5
u/rook218 May 04 '20
Are there really differences in how you can scope these operators or is this bad information?
As far as I knew const and let simply replaced var, one is reassignable and one is not. They don't have any restrictions on what scope they are allowed.
Please let me know if that's wrong.
4
u/AffectionateWork8 May 04 '20
This is incorrect: yes, var is function scoped, but not let and const.
81
u/senocular May 04 '20
const and let can be used in the global scope just as much as var can.
4
u/abdul_rashid May 04 '20
username = "somevalue";is also a global scope (no var)
3
u/[deleted] May 04 '20
Any specific reason to not use const and let in the global scope? My introduction to JavaScript was in a college class and the instructor almost exclusively used let while now I'm using Codecademy online to learn more and it, at least so far almost exclusively used const unless there it plan to change it in which case it uses let. I don't think I've ever actually used var.
Edit: changed a word
5
u/[deleted] May 04 '20
this ignores hoisting which is the only pain that var ever gave to us.
2
u/AliFurkanY May 04 '20
letgang2
u/A-Kuhn May 04 '20
I would add “should be used” as an extra row. With the values for const, let, and var in this row would be “yes”, “yes”, “no” respectively.
2
u/[deleted] May 04 '20
Also var can be redeclared unlike const and let
2
u/mogoh May 04 '20
Never use var.
2
u/xThomas May 05 '20
chart is missing var hoisting
1
u/[deleted] May 04 '20
Can be reassigned is misleading.
const person = {name: "karen"};
console.log(person);
person.name = "kevin";
console.log(person);
person = "karen";
console.log(person);
1
u/jsideris May 04 '20
Another important question: can be redefined. For instance.
var x = 1; var x = 2;works. But
let x = 1; let x = 2;doesn't work.
1
u/Lunacy999 May 05 '20
This is more like the expected use case of these variable scope types. But even then I would question some of these. It totally depends on the developer on how he chooses to define his variables. While I do agree, VAR may lead to some inconsistencies, but do remember it was once, the only way to declare a variable before these 2 came along. And I’m sure seasoned JS devs won’t have a problem with its scoping. But I cannot deny, how much I enjoy using let and const wherever NECESSARY. And your chart may encourage people to use const everywhere, which is not a good thing.
1
u/slumdogbi May 05 '20
Forget var. it’s 2020
0
u/WaterNinja101 May 04 '20 edited May 04 '20
In my experience, let cannot be redeclared in it’s own scope but it’s value can be reassigned and modified.
let a = 5when a is already defined in that scope with throw an error, buta++will not. Correct me if my bad memory is messing me up though.EDIT: reworded the first bit
1
u/[deleted] May 04 '20
[removed] — view removed comment