This question has already been answered:

Everywhere it is explicitly described that, unlike var - let/const have a block area of ​​visibility, but have encountered such a problem, I wonder what is connected with:

 let App = App || {}; App.init = function() { console.log('Inited'); } App.init(); // Uncaught ReferenceError: App is not defined (с const то же самое) 

 var App = App || {}; App.init = function() { console.log('Inited'); } App.init(); // 'Inited' 

Reported as a duplicate at Grundy. javascript 30 Dec '17 at 15:18 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

    2 answers 2

    We take and read the standard.

    The variables Let and Const are created in a running context and are not available exactly until their values ​​have been calculated during assignment. If there is no calculation, then by default they are assigned undefined.

    Var variables are created in context and immediately initialized to undefined, only then they are calculated.

    13.3 Declarations and the Variable Statement

    13.3.1 Let and Const Declarations

    NOTE and const declarations define the environment. It has been established that it has been assessed. It has been defined that it has been defined. It is not the case when the LexicalBinding is evaluated.

    13.3.2 Variable Statement

    Statement A var statement declares variables that are scoped to the running execution context's VariableEnvironment. Variables are created when they are created. BindingIdentifier can only declare one variable. It has been defined that it has been established.

    • In, it is so clearer that the difference is precisely in the "order of the tasks undefined". But still + for the right answer already given, do not seek, just a plus for clarification. - MedvedevDev
    • @MedvedevDev everything is fine, I do not worry about such occasions and do not chase the rating. The main thing is that the answer was helpful. - Alex Krass
    • @MedvedevDev Plus for you :) Why not - Oleg
    • @Grundy, log in! - user207618

    In the second case, the App is initialized and has undefined, and in the first case you have an error in the first line about an uninitialized variable.

    • This is all the js that is available. - MedvedevDev
    • one
      Before executing the code, the js engine is traversed and initializes variables that are declared through var and sets them to the value undefined. - Pasha Ivanov
    • That is, it turns out that let and var differ not only in the visibility zone, but also in how they work (apparently var searches for assigned variables and if not found, then sets undefined; and let just look for, but does not set anything)? .... interesting movie. - MedvedevDev
    • There are a lot of pitfalls in js, therefore it is better to read the relevant literature. - Pasha Ivanov