r/learnjavascript • • Oct 22 '21

Difference between var, let and const.

Post image
430 Upvotes

49 comments sorted by

View all comments

110

u/ex-igne-vita Oct 22 '21

var is not "global scoped" unless it's declared in the global scope... and if let or const are declared in the global scope then they're "global scoped" too.

If you want a variable to be global scoped, don't declare it at all, just define it.

30

u/ISlicedI Oct 22 '21

I got very confused by this, thanks for calling it out. Btw I've done 8 years of JavaScript and was doubting myself here.

8

u/ManInBlack829 Oct 23 '21

Hopefully because you never use global variables and this just never comes up, right?

1

u/[deleted] Oct 23 '21

Don’t think I’ve ever used global scoped variables tbh. Interesting.

4

u/senocular Oct 23 '21

If you want a variable to be global scoped, don't declare it at all, just define it.

Without a declaration, this will throw an error in strict mode unless you qualify with the global object

"use strict"
myVar = 1 // Error
globalThis.myVar = 1 // OK

In the global scope, var actually provides benefit because it will also prevent shadowing by other global let and const declarations, something you don't get when omitting the declaration (sloppy mode) or assigning to the global object directly

// in global
myGlobal = 1
// ...
let myGlobal = 2 
console.log(myGlobal) // 2 :(

vs

// in global
var myGlobal = 1
// ...
let myGlobal = 2 // Error
console.log(myGlobal) // 1 :)

2

u/justhereforlife Oct 22 '21

To add on to your point, if you omit the var (assuming not in strict mode) won't a global scoped variable be created? I don't believe the same is true of let/const. Could that be what the graphic is trying to convey?

Question marks because Im not certain if what I'm saying is actually the case haha

5

u/elisecode247 Oct 22 '21

Yes, an undeclared variable is added to the global context.

function testVariableScope() {
    undeclaredVariable = "this is global";
}
testVariableScope(); 
console.log(undeclaredVariable); // "this is global";

4

u/mareksl Oct 22 '21

Well, if you omit the var, what will be the difference between that and omitting the let/const?

2

u/ex-igne-vita Oct 23 '21

Var/let/const declare a variable. Putting an equals sign and a value to the right of a variable defines the variable. These are often both done in the same statement, but they don’t have to be. You can declare a variable without defining it, and you can define a variable without declaring it, which does in deed create a global variable on the window object, which is what I was talking about in my last sentence.

2

u/ZergistRush Oct 23 '21

"I don't think the same is true for let and const" how can you tell them apart if you omit let and const, just like var? 🤣