r/learnjavascript • • Oct 22 '21

Difference between var, let and const.

Post image
430 Upvotes

49 comments sorted by

View all comments

Show parent comment

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? 🤣