Explain difference between var, let and, const keywords

Explain difference between var, let and, const keywords

Apr 24, 2023 | Javascript

var, let, and const are all used to declare variables in JavaScript, but they differ in their scope, hoisting, and assignability.

  • var is used for variable declaration in pre-ES6 JavaScript. It has function scope, meaning that if it is declared inside a function, it is only accessible within that function. Variables declared with var can be hoisted, which means that they can be used before they are declared in the code. var variables can also be reassigned.

Example:

function example() {
  var x = 1;
  if (true) {
    var x = 2;
    console.log(x); // Output: 2
  }
  console.log(x); // Output: 2
}
  • let and const are introduced in ES6 (ECMAScript 2015) and have block scope. Block scope means that if a variable is declared inside a block (e.g., inside a loop or an if statement), it is only accessible within that block. Variables declared with let or const are not hoisted, which means that they cannot be used before they are declared. const variables cannot be reassigned, while let variables can.

Example:

function example() {
  let x = 1;
  if (true) {
    let x = 2;
    console.log(x); // Output: 2
  }
  console.log(x); // Output: 1
}

In summary, var has function scope, can be hoisted, and can be reassigned. let and const have block scope, cannot be hoisted, and const cannot be reassigned, while let can be. It is recommended to use let and const instead of var for better code readability and maintainability.

function example() {
  const x = 1;
  if (true) {
    const x = 2;
    console.log(x); // Output: 2
  }
  console.log(x); // Output: 1
}
Being Idea is a web platform of programming tutorials to make better programming skills and provides Software Development Solutions.

0 Comments

Leave a Reply