Why to avoid var and use let or const in JavaScript

Var and use let or const in JavaScript

In this Blog, We will learn about Var, Let, and Const and their related terminology. How are they used in block and function scope And why avoid using Var and use let or Const? In current JavaScript, it’s generally advocated to avoid var, and as an alternative, let or const for variable declarations.

Terminologies

Scopes in JS:

A Scope is where the declared variable can be accessed. There are 3 types of Scope in JavaScript.

  1. Global Scope refers to the javascript document where declared variables can be accessed anywhere in the code.
  2. Local Scope: refers to the variable that is declared inside the function. The Function is classified further into two types
    • Block Scope: A variable when declared inside the if or switch condition or inside the for or while loops.
    • Function Scope: A variable when declared inside the function,  the variable can’t be accessed outside the functions.

Why do we avoid Var?

1. Block Scope Vs Function Scope:

Var has a Function-Level Scope but the variable can be altered anywhere in the scope irrespective of the declaration. This behavior is called Hoisting. That means the variable declared with var can be accessed throughout the scope.

Example: here the example uses var and demonstrates how the name can be changed.

var name = "Rahul";
    
function newFunction() {
    var name = "Srisanth";
}

Another Example,

Function sayHello(name){
   console.log("Hello", name);
}

sayHello();
var name = "Srisanth";
2. Re-Statement

Var permits us re-assertion of identical variables with identical scope without mistake, which can lead to bugs and confusion. Let and Const do not allow re-assertion in the same scope, helping to prevent unintentional overwriting of variables.

Example:

var a = 1;
var a = 2;
console.Log(a); // 2

allow b = 1;
let b = 2; // SyntaxError: Identifier 'b' has already been declared
3. Hoisting

Var declarations are hoisted to the top of the scope meaning you can refer to them before the declarations in the code.

Example:

console.log(Number);  //undefined
var Number = 25;

The difference between Let, Const, and Var is that Var allows you to access the variable before declaration whereas Let and Const don’t. When a variable is declared in const it can’t be changed further and with Let it can be modified later but both of them are declared first and accessed later.

Furthermore, if you want you can check more blogs: Difference between var, let and const in JavaScript

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top