What is the difference between var, let, and const

In JavaScript, var, let, and const are used to declare variables but behave in different ways:

  • var: Declares a variable that is function-scoped or globally-scoped. It can be re-declared and updated.
  • let: Declares a block-scoped variable that can be updated but not re-declared in the same scope.
  • const: Declares a block-scoped variable that cannot be updated or re-declared. It must be initialized at the time of declaration.

Here’s an example demonstrating their differences:

// Var example var x = 1; if (true) { var x = 2; // Same variable console.log(x); // Outputs: 2 } console.log(x); // Outputs: 2 // Let example let y = 1; if (true) { let y = 2; // Different variable console.log(y); // Outputs: 2 } console.log(y); // Outputs: 1 // Const example const z = 1; // z = 2; // Error: Assignment to constant variable. console.log(z); // Outputs: 1

var let const javascript variables variable declaration