Chrome console already declared variables throw undefined reference errors for let

前端 未结 2 2040
傲寒
傲寒 2020-11-30 13:00

Recently I ran into this weird thing in chrome console. Here I am intentionally assigning an undefined thing to a in order to throw an error.

let a = werwr /         


        
2条回答
  •  天命终不由人
    2020-11-30 13:05

    This happens when you introduce the temporal dead zone to the global scope. As you might know, let declarations are hoisted but left uninitialised. Due to control flow, it can happen that a variable is never initialised:

    function …() {
        if (false)
            example; // would throw a ReferenceError if it was evaluated
        … // do something
        if (true)
            return; // stop!
        let example = 5; // never executed
    }
    

    This is fine in a function scope. Maybe something went wrong, maybe the variable wasn't needed at all - in the next call, a new scope with a new variable will be created.

    A similar thing can happen in the global scope, when you throw an exception before the variable is initialised (only exceptions work here as a control flow construct, nothing else achieves the same effect).

    throw new Error;
    let example = 5;
    

    In contrast to the function scope, it does matter here that the variable stays uninitialised. The global scope lasts forever, and the variable is eternally dead. It was not and will never be initialised, and lexical variables cannot be re-declared (which helps preventing mistakes).

    This was discussed on es-discuss, but deemed irrelevant. If top-level

提交回复
热议问题