r/learnjavascript • • May 04 '20

VAR vs LET vs CONST

Post image
337 Upvotes

81 comments sorted by

7

u/NoFapPlatypus May 04 '20

What does block scope mean?

12

u/golovatuy May 04 '20

{ } this a block , everything inside is block scope

5

u/NoFapPlatypus May 04 '20

Ok thank you

2

u/spainzbrain May 04 '20

I was about to ask the same thing.

-1

u/PenisPistonsPumping May 04 '20

I don't mean any offense, but maybe you should get a better grasp on JavaScript before you make educational stuff.

This is JavaScript 101.

1

u/HeinousTugboat May 04 '20

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.

1

u/PenisPistonsPumping May 04 '20

I'm talking about the global scope part.

8

u/Macaframa May 04 '20

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.

1

u/NoFapPlatypus May 04 '20

Thank you that is helpful

2

u/Macaframa May 04 '20

You’re welcome, I know that guy just sort of replied with the bare minimum and sometimes we require a little more deep level of understanding.

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.

3

u/golovatuy May 04 '20

Scope is the main difference between var and let

4

u/rook218 May 04 '20

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();

5

u/Coraline1599 May 04 '20

Try this:

{
var v = 'hi'
let l = 'hello'
}
console.log(v)
console.log(l)

you can log `v` but `l` will error, because the scope is limited to the block when using let.

The curly braces are a block (this could also be part of a for loop, function, etc)

Again you can log `j` outside the loop, but `i` will give you undefined:

for (var j = 0; j < 3; j++) {
  console.log(j)
}

console.log(j)

for (let i = 0; i < 3; i++) {
  console.log(i)
}

console.log(i)

4

u/AffectionateWork8 May 04 '20

This is incorrect: yes, var is function scoped, but not let and const.

-3

u/golovatuy May 04 '20

Const, var and let are not visible outside the function

3

u/AffectionateWork8 May 04 '20 edited May 05 '20

"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:

  1. 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.

  2. 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.

  3. 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.

function doStuff() {

console.log(fnScoped) // undefined

console.log(blockScoped) // Reference Error

if (true) {

var fnScoped = 'hi!'

let blockScoped = 'hello'

}

console.log(blockScoped) // Reference error

console.log(fnScoped) // 'hi'

}

doStuff()

81

u/senocular May 04 '20

const and let can be used in the global scope just as much as var can.

32

u/redsandsfort May 04 '20

agree. this chart is bad info

-2

u/[deleted] May 04 '20

You guys should make a new more comprehensive chart then. For real, it would be much appreciated!

0

u/[deleted] May 04 '20

[deleted]

1

u/[deleted] May 05 '20

then why bother about var?

3

u/schm0 May 05 '20

Backwards compatible (ES5-), no memory concerns? If you're using ES6+ there's no reason, honestly.

-3

u/Pythagoras_was_right May 04 '20

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.

10

u/dwb5226 May 04 '20 edited May 04 '20

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:

const obj = {a: 1, b: 2}
obj["b"] = 3
console.log(obj) // {a: 1, b: 3}

and it'll run fine

1

u/[deleted] May 05 '20

I write about this ön my blog: http://herebeseaswines.net/essays/2019-05-25-airiness-of-const-and-freeze

As you say - it is possible to mutate stuff! Strange indeed

1

u/[deleted] May 09 '20

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.

0

u/[deleted] May 04 '20

[deleted]

3

u/Pythagoras_was_right May 04 '20

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!

2

u/thuwie May 07 '20

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.

18

u/cyphern May 04 '20

By "global scope" I think they mean "secretly copies your variable to the window object"

2

u/redsandsfort May 04 '20

it doesn't

function fn(){
var x = 'cool';
return x + 'dude';

}

console.log(windox.x) // undefined

2

u/cyphern May 04 '20

You're correct that the behavior i mentioned doesn't happen for local variables.

1

u/VacantPlains May 04 '20

Do you have an example of that?

3

u/cyphern May 04 '20
var a = "hello world";
console.log(window.a); // hello world

2

u/redsandsfort May 04 '20

const and let would also be global if outside of a function

1

u/VacantPlains May 04 '20

Oh I see! Thanks

3

u/Earhacker May 04 '20

Meanwhile...

const b = "foo";
console.log(window.b); // undefined
let c = "bar";
console.log(window.c); // undefined

2

u/redsandsfort May 04 '20

const b = "foo";
console.log(window.b); // undefined
let c = "bar";
console.log(window.c); // undefined

If you logged it like this:
console.log(b);

it would still be global if it isn't in a function

5

u/Earhacker May 04 '20

It would have global scope, sure. But it wouldn't be an entry in the global object, is the point I was trying to make.

1

u/schm0 May 05 '20

I think they are confusing variable hoisting with global scope?

1

u/senocular May 05 '20

const and let also hoist.

-3

u/Macaframa May 04 '20

This should say

let, const: block scoping

const: non-writable once it’s instantiated

let: only real use is in a for loop

-7

u/MrSandyClams May 04 '20

I use let 100% of the time. Reasoning: the word "const" is ugly to look at

7

u/Macaframa May 04 '20

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.

  • sincerely a disgruntled developer

-2

u/runamok May 04 '20

I think you mean: var: only real use is in a for loop ???

1

u/Macaframa May 04 '20

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.

2

u/MoTTs_ May 04 '20

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.

1

u/Macaframa May 04 '20

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.

2

u/MoTTs_ May 04 '20 edited May 16 '20

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.

Doc link: https://www.ecma-international.org/ecma-262/10.0/index.html#sec-createperiterationenvironment

0

u/[deleted] May 04 '20

[deleted]

4

u/senocular May 04 '20

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/cyphern pointed 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:

keywordconstletvar
global scopeYESYESYES
function scopeYESYESYES
block scopeYESYESNO
adds to global object if in global scopeNONOYES
can redeclare itselfNONOYES
can be read before declaredNONOYES
must be initialized with a valueYESNONO
can be reassignedNOYESYES

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.

4

u/abdul_rashid May 04 '20

username = "somevalue";

is also a global scope (no var)

6

u/Unique_2233 May 04 '20

I guess if no type is specified it implicitly is converted to var

3

u/proskillz May 04 '20

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.

4

u/senocular May 04 '20

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";.

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

1

u/rook218 May 04 '20

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).

1

u/[deleted] May 04 '20

Dan Abramov recommends only using let, for what it's worth.

1

u/HeinousTugboat May 04 '20

What's his reasoning behind that? He hates letting optimizing compilers optimize?

1

u/[deleted] May 05 '20

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.

1

u/BackhandCompliment May 05 '20

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.

1

u/BackhandCompliment May 05 '20

Though I just looked it up, and this is what he actually said:

My Conclusion

I don’t care.

I would use whatever convention already exists in the codebase.

5

u/[deleted] May 04 '20

this ignores hoisting which is the only pain that var ever gave to us.

2

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 = 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.

EDIT: reworded the first bit

2

u/[deleted] May 04 '20

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.

a++; is in fact just a = a + 1;

2

u/WaterNinja101 May 04 '20

Ah okay. That was the distinction I was looking for, just was not sure what the proper terminology was.

2

u/proskillz May 04 '20

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.

1

u/[deleted] May 04 '20

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.

1

u/proskillz May 04 '20

How does that refute anything I said?

1

u/[deleted] May 04 '20

It doesn't refute your statement. But you have to see, that the mutability is shared between all three types of declaration.

1

u/[deleted] May 04 '20

[removed] — view removed comment

1

u/Michael35699 May 04 '20
function main() {
    { // Start of new block
        let fooLet = 0;
        var fooVar = 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.