Javascript variables: the idea behind var, let, and const

JavaScript Variables: The idea behind Var, Let, and Const

Is var, let and const are different?? And if yes then how?? You might have had heard this question in every JavaScript interview. Let’s understand the idea behind it.

In JavaScript to store any data into the variable, you must know the following things.

  1. Declaration of variable // let a;
  2. Initialization of variable // a = 5;
  3. Reassignment of value // a = 8;

With this declaration and initialization, we need to know the variable’s scope to better understand program execution.

  1. Program (Global) Scope — valid for the whole program.
  2. Block (Local) Scope — valid only to the block.

Note: If any variable is declared without any keyword it has a program (global) scope.

if(true) {
    a = 20;
    console.log(a); // 20 — block scope
}
console.log(a); // 20 — program scope

Note: Whenever there is a contradiction between local and global variables, the local variable gets precedence.

let a = 10;
if(true) {
    let a = 20;
    console.log(a); // 20
}
console.log(a); // 10

Var

1. Program Scoped: Any variable declared with var keyword its program scoped and accessible globally.

if(true) {
    var a = 20;
    console.log(a); // 20
}
console.log(a); // 20

2. Double declaration: Variable can be declared twice with the same name with the var keyword, but it will take the value of the latest declaration.

var a = 10;
var a = 20;
console.log(a); // 20

3. Hoisting: Hoisting is allowed only with the var keyword.

a = 20;
console.log(a); // 20
var a; // hoisted to top of the program.

4. Declaration, Initialization, and reassignment are possible.

Let

1. Block scoped: Any variable declared with the let keyword is blocked scoped, and only accessible in a particular block(locally).

if(true) {
    let a = 20;
    console.log(a); // 20
}
console.log(a); // error

2. Double declaration is not allowed.

let a = 10;
let a = 20; // error

3. Hoisting doesn’t support it.

a = 20;
console.log(a); // 20
let a; // error

4. Declaration, Initialization, and reassignment are possible.

Const

1. Block scoped: Any variable declared with the const keyword is blocked scoped, and only accessible in a particular block(locally).
2. The double declaration is not allowed.
3. Hoisting doesn’t support it.
4. Declaration and Initialization must be at the same time and reassignment is not possible.

const PI = 3.14;
PI = 5.19; // error

Note: Const is the same as the let keyword, but as constants used to store never-changing values, it doesn’t support points 2, 3, 4. Usually, constants are named with CAPITAL letters.

Conclusion

As per the best practices, we should avoid using the var keyword, instead go for let and const keywords as needed.

You Might Also Like
%d bloggers like this: