Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a `let` variable has been declared on ES6?

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

like image 322
Royi Namir Avatar asked Jun 25 '15 06:06

Royi Namir


2 Answers

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 vars.

But you're right, in contrast to vars 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 vars1. 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.

like image 98
Bergi Avatar answered Oct 23 '22 02:10

Bergi


That would be the closest to what you are looking for:

try {
    console.log(typeof mima); // or any other use of variable
    let mima = 'no ni ma';
} catch (error) {
    console.log(error); // “Uncaught ReferenceError: mima is not defined(…)”

    // and then taking some actions regarding the situation
}

Though, its usefulness is rather debatable. But if I had to check let’ed variable, I would go with something like that. However, mind you that you cannot safely create missing variable with let, as it’s surrounded by catch block. But it will not break the code.

like image 26
The Witness Avatar answered Oct 23 '22 02:10

The Witness