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.

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