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.
-
vardeclares a variable with function scope or global scope if declared outside a function. Variables declared withvarare hoisted, meaning they are accessible before their declaration but with the valueundefined. They can be redefined and reassigned. -
letdeclares 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. -
constalso 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.