Reputation: 21
Javascript novice here. From https://www.freecodecamp.org/news/var-let-and-const-whats-the-difference/ :
So "const" is clear that it's initialized as the value it was originally declared as.
"var":
a) not declared, initialized as undefined
b) declared, initialized accordingly
"let":
a) not declared, initialized as ______???______
b) declared, initialized accordingly
What is "let" initialized as if it's not declared at first?
Upvotes: 2
Views: 3530
Reputation: 597
Well, the easiest way to think about it is that there is only 1 type of undeclared variable (in the sense of never declared, otherwise you just get a ReferrenceError
). If it is never declared, the JavaScript engine can't be choosing to make it a var
or a let
or a const
to fit the developer needs.
Any never declared variable that is assigned a value becomes a global scope variable (ref: comment from Avikalp Gupta)
Upvotes: 0
Reputation: 215059
Hoisted let
variables are initialized with a special "value" that throws a ReferenceError
when accessed:
function foo() {
console.log(x) // ReferenceError: Cannot access 'x' before initialization
let x
}
foo()
let and const declarations define variables that are scoped to the running execution context's LexicalEnvironment. The variables ... may not be accessed in any way until the variable's LexicalBinding is evaluated.
Upvotes: 0
Reputation: 9
let if declared and not initialized, then its default value is set to undefined.
let x;
console.log(x);
>> undefined
Upvotes: 1