Home >Web Front-end >JS Tutorial >Characteristics of let and const

Characteristics of let and const

yulia
yuliaOriginal
2018-09-08 16:09:411553browse

Characteristics of let:

1. There is no variable promotion phenomenon: that is, if it is used before declaration, a ReferenceError will be reported. Works with for loop counters.
2. Temporary dead zone: that is, using let to declare a variable in a block-level scope, the variable can only be used in that scope.
3. Repeated declarations are not allowed: variables declared by let cannot be declared again, otherwise an error will be reported.

Characteristics of const:

1. There is no variable promotion phenomenon.
2. Temporary dead zone.
3. Repeatable statements are not allowed.
4. What is declared is a read-only constant, which must be initialized when declared.
5. What is essentially stored is the memory address. The value of simple type data is stored in this address. The value of composite type data is stored in this address as a pointer. The object pointed to by this pointer can be changed, but a single pointer cannot be changed.

cost foo = {};
// 可以改变foo的属性
foo.prop = 123;
foo.prop  //123
// 不可以使foo指向别的对象
foo = {}; //TypeError: "foo" is read-only

Freeze object:

// 彻底冻结
var constantize = (obj) => {
   Object.freeze(obj);
   Object.keys(obj).forEach( (key, i) => {
       if( typeof obj[key] === 'object' ){
         constantize( obj[key] );
       }
    });
}

The above is the detailed content of Characteristics of let and const. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Related articles

See more