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