What is the difference between 'let' and 'const' ECMAScript 2015 (ES6)?

孤街醉人 提交于 2019-11-26 17:37:50

What you're seeing is just an implementation mistake. According to the ES6 spec wiki on const, const is:

A initialize-once, read-only thereafter binding form is useful and has precedent in existing implementations, in the form of const declarations.

It's meant to be read-only, just like it currently is. The ES6 implementation of const in Traceur and Continuum are buggy (they probably just overlooked it)

Here's a Github issue regarding Traceur not implementing const

The difference between let and const is that once you bind a value/object to a variable using const, you can't reassign to that variable. Example:

const something = {};
something = 10; // Error.

let somethingElse = {};
somethingElse = 1000; // This is fine.

Note that const doesn't make something immutable.

const myArr = [];
myArr.push(10); // Works fine.

Probably the best way to make an object (shallowly) immutable at the moment is to use Object.freeze() on it.

let

  • Use block scope in programming.
  • for every block let create its own new scope which you cannot access in outside of that block.
  • value can be changed as many times as you want.
  • let is extremely useful to have for the vast majority of code. It can greatly enhance your code readability and decrease the chance of a programming error.

    let abc = 0;
    
    if(true)
     abc = 5 //fine
    
    if(true){
      let def = 5
    }
    console.log(def)
    

const

  • It allows you to be immutable with variables.
  • const is a good practice for both readability and maintainability and avoids using magic literals e.g.

    // Low readability
    if (x > 10) {
    }
    
    //Better!
    const maxRows = 10;
    if (x > maxRows) {
     }
    
  • const declarations must be initialized

     const foo; // ERROR: const declarations must be initialized
    
  • A const is block scoped like we saw with let:+
const foo = 123;
if (true) {
    const foo = 456; // Allowed as its a new variable limited to this `if` block
}

Summary:

Both the let and the const keyword are ways to declare block scoped variables. There is one big difference though:

  • Variables declared with let can be reassigned.
  • Variables declared with const have to be initialized when declared and can't be reassigned.

If you try to reassign variables with declared with the const keyword you will get the following error (chrome devtools):

Why should we use this?

If we know that we want to assign a variable once and that we don't want to reassign the variable, using the const keywords offers the following advantages:

  • We communicate in our code that we don't want to reassign the variable. This way if other programmmers look to your code (or even you to your own code you wrote a while ago) you know that the variables which are declared with const should not be reassigned. This way our code becomes more declarative and easier to work with.
  • We force the principle of not being able to reassign a variable (JS engine throws error). This way if you accidentally try to reassign a variable which is not meant to be reassigned you can detect this at an earlier stage (because it's logged to the console).

Caveat:

Although a variable declared with const can't be reassigned this doesn't mean that an assigned object isn't mutable. For example:

const obj = {prop1: 1}

// we can still mutate the object assigned to the 
// variable declared with the const keyword
obj.prop1 = 10;
obj.prop2 = 2;

console.log(obj);

If you also want your object to be non mutable you can use Object.freeze() in order to achieve this.

let and const

Variables declared with let and const eliminate specific issue of hoisting because they’re scoped to the block, not to the function.

If a variable is declared using let or const inside a block of code (denoted by curly braces { }), then the variable is stuck in what is known as the temporal dead zone until the variable’s declaration is processed. This behavior prevents variables from being accessed only until after they’ve been declared.

Rules for using let and const

let and const also have some other interesting properties.

  • Variables declared with let can be reassigned, but can’t be redeclared in the same scope.
  • Variables declared with const must be assigned an initial value, but can’t be redeclared in the same scope, and can’t be reassigned.

Use cases

The big question is when should you use let and const? The general rule of thumb is as follows:

  • use let when you plan to reassign new values to a variable, and
  • use const when you don’t plan on reassigning new values to a variable.

Since const is the strictest way to declare a variable, it is suggest that you always declare variables with const because it'll make your code easier to reason about since you know the identifiers won't change throughout the lifetime of your program. If you find that you need to update a variable or change it, then go back and switch it from const to let.

Here are some notes that I took that helped me on this subject. Also comparing const and let to var.

Here's about var:

// Var
// 1. var is hoisted to the top of the function, regardless of block
// 2. var can be defined as last line and will be hoisted to top of code block
// 3. for undefined var //output error is 'undefined' and code continues executing
// 4. trying to execute function with undefined variable
// Example: // log(myName); // output: ReferenceError: myName is not defined and code stops executing 

Here's about let and const:

// Let and Const
// 1. use `const` to declare variables which won't change
// 2. `const` is used to initialize-once, read-only thereafter
// 3. use `let` to declare variables which will change
// 4. `let` or `const` are scoped to the "block", not the function
// 5. trying to change value of const and then console.logging result will give error
// const ANSWER = 42;
// ANSWER = 3.14159;
// console.log(ANSWER);
// Error statement will be "TypeError: Assignment to constant variable." and code will stop executing
// 6. `let` won't allow reference before definition
// function letTest2 () {
//   log(b);
//   let b = 3;}
// Error statement will be "ReferenceError: b is not defined." and code will stop executing

ES6 let and const

The new let allows you to declare a variable that is limited in scope to the block (Local variable). The main difference is that the scope of a var variable is the entire enclosing function:

if (true) {
  var foo = 42; // scope globally
}

console.log(foo); // 42

Using let in Scope:

if (true) {
  let foo = 42; // scoped in block
}

console.log(foo); // ReferenceError: bar is not defined

Using var in function scope is the same as using let:

function bar() {
  var foo = 42; // scoped in function
}

console.log(foo); // ReferenceError: bar is not defined

The let keyword attaches the variable declaration to the scope of whatever block it is contained in.

The Declaration Order Difference

Another difference between let and var is the declaration/initialization order. Accessing a variable declared by let earlier than its declaration causes a ReferenceError.

console.log(a); // undefined
console.log(b); // ReferenceError: b is not defined

var a = 1;
let b = 2;

Using const

On the other hand, using ES6 const is much like using the let, but once a value assigned, it cannot be changed. Use const as an immutable value to prevent the variable from accidentally re-assigned:

const num = 42;

try {
  num = 99;
} catch(err) {
  console.log(err);
  // TypeError: invalid assignment to const `number'

}

num; // 42

Use const to assign variables that are constant in real life (e.g. freezing temperature). JavaScript const is not about making unchangeable values, it has nothing to do with the value, const is to prevent re-assigning another value to the variable and make the variable as read-only. However, values can be always changed:

const arr = [0, 1, 2];
arr[3] = 3; // [0, 1, 2, 3]

To prevent value to be change, use Object.freeze():

let arr = Object.freeze([0, 1, 2]);
arr[0] = 5;

arr; // [0, 1, 2]

Using let with For Loop:

A particular case where let is really useful, is in the header of for loop:

for (let i = 0; i <= 5; i++) {
  console.log(i);
}

// 0 1 2 3 4 5

console.log(i); // ReferenceError, great! i is not global

This also can be applied for other loops, like for...in and for...of.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!