Sobes.tech
Middle

What are the ways to declare variables in JavaScript and what is the difference?

sobes.tech AI

Answer from AI

In JavaScript, variables can be declared using three keywords: var, let, and const.

  • var declares a variable with function scope or global scope if declared outside a function. Variables declared with var are hoisted, meaning they are accessible before their declaration but with the value undefined. They can be redefined and reassigned.

  • let declares a variable with block scope. It is not hoisted and is only accessible after its declaration. It can be reassigned but not re-declared within the same block.

  • 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:

function example() {
  if (true) {
    var a = 1;
    let b = 2;
    const c = 3;
  }
  console.log(a); // 1
  console.log(b); // ReferenceError
  console.log(c); // ReferenceError
}

Thus, let and const are preferred in modern code as they help avoid issues related to scope and hoisting.

What are the ways to declare variables in JavaScript… - sobes.tech