Differentiate between var and let in JavaScript

Tram Ho

1. Differentiate between var and let in JavaScript

Distinguish
Var
Let
Alike
All are keywords – keywords. The same is used to declare variables in JavaScript
——–
——–
——–
Difference
The scope of the variable using var is function scope or outside the function, global.The scope of a variable using let is a block scope, defined by the pair {}.
The variable var can be updated and re-declared in the scope of existence.The let variable can be updated but cannot be re-declared.
can be declared without initialization.can be declared without initialization.
can be accessed without initialization because its default value is “undefined”.cannot be accessed without initialization, as it returns an error.
General distinction between var and let

Table of differences of two variables var, let.

2. Var

2.1 Declare with Var keyword:

The let variable can be updated but cannot be re-declared

2.2 Operational scope:

Global scope or Function scope. The scope of the var keyword is either the global scope or the Function scope. It means that variables defined outside the function can be accessed globally and variables defined inside a particular function can be accessed inside the function. Check out the LPTech examples below

2.3 Example:

  • Example 1 : The variable ‘a’ is declared globally. So the scope of variable ‘a’ is global and it can be accessed anywhere in the program.

Result:

  • Example 2 : The variable ‘a’ is declared inside the function. If the user tries to access it outside the function, it will display an error. Users can declare 2 variables with the same name using the var keyword. Alternatively, the user can reassign the value to the variable var.

Result:

  • Example 3 : User can re-declare variable with var and user can update variable var.

Result:

  • Example 4 : If the user uses the variable var before declaring it, the variable will be initialized with an undefined value.

Result:

3. Let

3.1 Declare with the Let keyword:

The let keyword is an improved version of the var keyword.

3.2 Scope of work:

The scope of a let variable is just block scope. It is not accessible outside the specific block ({block}). Check out the LPTech examples below.

3.3 Example:

  • Example 1 :

  • Example 2 : The code returns an error because we are accessing the let variable outside the function block.

Result:

  • Example 3 : User cannot re-declare a variable defined with the let keyword but can update it.

  • Example 4 : Users can declare variables with the same name in different blocks using the let keyword.

4. Should I use var or let?

  • Từ khóa var đã lỗi thời . The let keyword should only be used to declare variables.
  • From ES6 version, mình khuyên bạn chỉ nên dùng từ khóa let.

Refer:

Share the news now

Source : Viblo