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
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 withundefined
immediately, only when thelet
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 aReferenceError
when used.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.