Difference between let/const and var [duplicate]

This question is already answered here: Do variables declared with let and const pop up in ES6? (1 answer) Closed 3 years ago.

Everywhere it is explicitly described only that, in contrast to var - let/const they have a block scope, but I ran into such a problem, I wonder what is connected with it:

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'
Author: MedvedevDev, 2017-08-26

2 answers

We take and read the standard.

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

Var variables are created in the context and immediately initialized with the value undefined, only then they are evaluated.

13.3 Declarations and the Variable Statement

13.3.1 Let and Const Declarations

NOTE let and const declarations define variables that are scoped to the running execution context’s LexicalEnvironment. The variables are created when their containing Lexical Environment is instantiated but may not be accessed in any way until the variable’s LexicalBinding is evaluated. A variable defined by a LexicalBinding with an Initializer is assigned the value of its Initializer’s AssignmentExpression when the LexicalBinding is evaluated, not when the variable is created. If a LexicalBinding in a let declaration does not have an Initializer the variable is assigned the value undefined when the LexicalBinding is evaluated.

13.3.2 Variable Statement

NOTE A var statement declares variables that are scoped to the running execution context’s VariableEnvironment. Var variables are created when their containing Lexical Environment is instantiated and are initialized to undefined when created. Within the scope of any VariableEnvironment a common BindingIdentifier may appear in more than one VariableDeclaration but those declarations collective define only one variable. A variable defined by a VariableDeclaration with an Initializer is assigned the value of its Initializer’s AssignmentExpression when the VariableDeclaration is executed, not when the variable is created.

 7
Author: Alex Krass, 2017-08-26 23:21:51

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

 3
Author: Паша Иванов, 2017-08-26 22:59:19