Sobes.tech
Middle

What is the difference between const, let, and var?

sobes.tech AI

Answer from AI

var, let, and const are three ways to declare variables in JavaScript, differing in scope and reassignability.

  • var declares a variable with function or global scope. Variables can be reassigned and redeclared. It is subject to hoisting.

  • let has block scope (e.g., inside {}). The variable can be reassigned but not redeclared in the same scope. It is not subject to hoisting.

  • const also has block scope, but the variable must be initialized immediately and cannot be reassigned. However, if it is an object or array, its contents can be modified.

Example:

var a = 1;
let b = 2;
const c = 3;

b = 4; // OK
// c = 5; // Error

if (true) {
  var a = 10; // will overwrite the outer a
  let b = 20; // new variable within the block
}
console.log(a); // 10
console.log(b); // 4
What is the difference between const, let, and var… - sobes.tech