Unlike traditional var-declared variables, which are attached to the entire enclosing, function scope regardless of where they appear — let
declarations attach to the block scope but are not initialized until they appear in the block
So :
console.log( a ); // undefined
console.log( b ); // ReferenceError!
var a;
let b;
So it seems that hoisting is not applied here.
Question
If so , how can I safely check if the variable has been declared ?
NB - The option I see is try/catch and of course always put the let
variables first at scope. but still my question remains
it seems that hoisting is not applied here.
Not exactly. The variable still covers the complete scope, the binding is created when the scope is entered just like with var
s.
But you're right, in contrast to var
s it is not initialised with undefined
immediately, only when the let
statement is evaluated. The area from the top of the scope to there is called temporal dead zone - the identifier is bound, but will always throw a ReferenceError
when used.
How can I safely check if the variable has been declared?
You cannot, just as you cannot for var
s1. You don't need this anyway.
1: Let's ignore global variables2 that become properties of the global object here.
2: var
/function
/function*
-declared variables, I mean. Lexical bindings (let
, const
) indeed don't become global properties.