This is the 16th day of my participation in the August Genwen Challenge.More challenges in August
Variable declarations
Before ES6, var was the only keyword used to declare variables. Not only did ES6 add the let and const keywords, it also made them overwhelmingly preferred over var.
Use the block-level scope declaration for lets
The new LET keyword in ES6 is similar to VAR, but the scope of let is block-level. The block-level scope is determined by the nearest pair of curly braces {}.
if(true) {let a = 1;
}
console.log(a) //ReferenceError: A is not defined
Copy the code
Let differs from var in that it cannot be declared twice in the same scope. Duplicate var declarations are ignored, and duplicate let declarations raise SyntaxError. Strictly speaking, let is actually promoted while JavaScript is running, but because of “temporary dead zones” you can’t actually use let variables before declaration. Therefore, from the standpoint of writing JavaScript code, let is not promoted in the same way as VAR.
Use a const constant declaration
In addition to let, ES6 also added the const keyword. Variables declared using const must be initialized to a value at the same time. Const declarations apply only to top-level primitives or objects.
const o1 = {};
o1 = {}; // TypeError: Assigns values to constants
const o2 = {};
o2.name = 'Jujin';
console.log(o2.name); // 'Jujin'
Copy the code
Identifier lookup
When an identifier is referenced for reading or writing in a particular context, a search must be performed to determine what the identifier represents. The search starts at the front of the scope chain, searching for the corresponding identifier by the given name. If the identifier is found in the local context, the search stops and the variable is determined. If the variable name is not found, the search continues along the scope chain. (Note: Objects in the scope chain also have a prototype chain, so a search may involve the prototype chain of each object.) This process continues until the variable object is searched to the global context, and if the identifier is still not found, it is undeclared.
Note that accessing local variables is faster than accessing global variables because you don’t have to switch scopes. However, JavaScript engines do a lot of work to optimize identifier look-ups, and the difference may be insignificant later on.