0

JavaScript (ES-2015) Variables: let and const

Variables: let and const

Now i have a project, where people don't think and use let o const without any understanding in wich case they should to use one of them. This post about let and const in JavaScript, please read and try to understand difference between of them.

In ES-2015 there are new ways of declaring variables: let and const instead of var.

var a = 5 // old format

let a = 5; // new format: variable

const a =5 // new format: constant

let

Declaring a variable with let has three main differences from var:

1. The scope of the let variable is the block {...}

As we remember, a variable declared via var is visible everywhere in the function.

The variable declared through let is visible only within the block {...}, in which it is declared.

This, in particular, affects ads inside if, while, or for.

For example, a variable via var:

var apples = 5;

if (true) {
  var apples = 10;

  alert(apples); // 10 (inside block)
}

alert(apples); // 10 (outside block - the same value)

In the example above, apples is one variable for all code that is modified in if.

The same with let will work differently:

let apples = 5; // (*)

if (true) {
  let apples = 10;

  alert(apples); // 10 (inside block)
}

alert(apples); // 5 (outside block - value is didn't chanched)

Here, in fact, there are two independent variables apples, one is global, the second is in the if block.

Note that if the let apples statement in the first line (*) is deleted, then the last alert will have an error: the variable is not defined:

If (true) {
   Let apples = 10;

   Alert (apples); // 10 (inside the block)
}

Alert (apples); // error!

This is because the variable let is always visible in the block where it is declared, and no more.

2. The variable let is visible only after the declaration.

As we remember, var variables also exist before the declaration. They are undefined:

alert(a); // undefined

var a = 5;

With variables let all is easier. Before they are announced, there is none at all.

Such access will lead to an error:

alert(a); // error, variable is not exist

let a = 5;

Note: also that let variables can not be re-declared. That is, this code will output an error:

let x;
let x; // Error: x variable already declared

This - although it looks like a constraint in comparison with var, but in fact does not create a problem. For example, two such cycles do not conflict at all:

// Each cycle has its own variable i
for(let i = 0; i<10; i++) { /* … */ }
for(let i = 0; i<10; i++) { /* … */ }

alert( i ); // Error: global i is not present

When declaring within a loop, the variable i will be visible only in the block of the loop. It is not visible outside, so there is an error in the last alert.

3. When used in a loop, a variable is created for each iteration.

The variable var is one for all iterations of the loop and is visible even after the loop:

for(var i=0; i<10; i++) { /* … */ }

alert(i); // 10

With the variable let - everything is different.

Each repetition of the loop has its own independent variable let. If inside the loop there are nested declarations of functions, then in the closure of each there will be that variable that was with the corresponding iteration.

This makes it easy to solve the classical closure problem described in the Army of Functions problem.

function makeArmy() {

  let shooters = [];

  for (let i = 0; i < 10; i++) {
    shooters.push(function() {
      alert( i ); // displays his number
    });
  }

  return shooters;
}

var army = makeArmy();

army[0](); // 0
army[5](); // 5

If the declaration was var i, then there would be one variable i for the entire function, and calls in the last lines would output 10 (for more details see the function army function).

And above let i creates each variable for the loop in the loop, which the function receives from the closure in the last lines.

const

The declaration const specifies a constant, that is, a variable that can not be changed:

const apple = 5;
apple = 10; // **ERROR**

Otherwise, the const declaration is completely analogous to let.

Note that if an object is assigned to a constant, then the constant itself is protected from the change, but not the properties inside it:

const user = {
  name: "Jack"
};

user.name = "Jamie"; // it's ok
user = 5; // no, will be error

The same is true if a constant is assigned an array or another object value.

constants and CONSTANTS

Constants that are hard-coded always, during the whole program, are usually written in uppercase. For example: const ORANGE = "# ffa500".

Most variables are constants in a different sense: they do not change after assignment. But at different starts of function this value can be different. For such variables, you can use const and the usual lowercase letters in the name.

Total

Let variables:

  • Are visible only after the announcement and only in the current block.
  • You can not re-advertise (in the same block).
  • When declaring a variable in the for (let ...) loop, it is visible only in this loop. Each
  • iteration has its own variable let.

The variable const is a constant, otherwise it is let.


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí