What are the differences between var, let, and const?

What are the differences between var, let, and const?

In JavaScript, var, let, and const are used to declare variables, but they have different scoping rules and behaviors. Here’s a detailed explanation of the differences between them:

var:

Variables declared with var are function-scoped or globally-scoped.

They are hoisted to the top of their scope, which means they can be accessed before they are declared.

var allows redeclaration and reassignment of variables.

Example:

function example() {

  var x = 10;

  if (true) {

    var x = 20;

    console.log(x); // Output: 20

  }

  console.log(x); // Output: 20

}

let:

Variables declared with let are block-scoped, which means they are limited to the block in which they are defined (e.g., inside loops or conditionals).

They are not hoisted, and accessing them before they are declared will result in a reference error.

let allows reassignment of variables but does not allow redeclaration within the same block scope.

Example:

function example() {

  let x = 10;

  if (true) {

    let x = 20;

    console.log(x); // Output: 20

  }

  console.log(x); // Output: 10

}

const:

Variables declared with const are also block-scoped.

They are not hoisted and must be assigned a value at the time of declaration.

const variables are read-only, and their values cannot be reassigned once they are initialized.

const does not allow redeclaration within the same block scope.

However, for objects and arrays declared with const, their properties or elements can still be modified.

Example:

function example() {

  const x = 10;

  if (true) {

    const x = 20;

    console.log(x); // Output: 20

  }

  console.log(x); // Output: 10

}

const person = {

  name: ‘John’,

  age: 30

};

person.age = 31; // Valid, modifying object property

person = {}; // Invalid, reassignment of const variable

In general, it is recommended to use let and const over var because they offer better scoping and help prevent unintended redeclarations and bugs. Use let when you need to reassign a variable, and use const when you want to declare a constant value that should not be modified.

It’s worth noting that let and const were introduced in ECMAScript 2015 (ES6) and have better scoping rules compared to the older var keyword. Therefore, if you’re working with newer versions of JavaScript, it is generally advisable to prefer let and const for more predictable and maintainable code.