In JavaScript, "var", "let", and "const" are used for variable declarations, and they have different scoping rules and behaviours.
Variables declared with var are function-scoped, meaning they are visible throughout the entire function in which they are declared.
If declared outside any function, they have global scope.
Variables declared with var are hoisted to the top of their scope, allowing them to be accessed before their declaration. However, the value is not hoisted, leading to potential issues.
console.log(count); // count is `undefined` var count = 5;
Variables declared with var can be redeclared within the same scope without causing an error.
{ var count = 100; var count = 120; console.log(count) // Output: 120 }
Variables declared with let have block scope, which means they are limited to the block (enclosed by curly braces) in which they are defined.
Block scope includes loops, conditionals, and functions.
// console.log(count); // Error: Cannot access `count` before initialization let count = 5;
Variables declared with let are not hoisted to the top of their block, and they are not accessible before their declaration.
Variables declared with let cannot be redeclared within the same block scope.
If we try to re-declare the variable within the same block scope, we will encounter an error `SyntaxError: Identifier 'count' already been declared`.
{ let count = 100; let count = 120; // it will throw an error console.log(count) }
Like let, const also has block scope.
Variables declared with const are not hoisted, similar to let.
If we try to access the variable before declaration and intialization, we encounter an error such as `ReferenceError: Cannot access 'count' before initialization`.
// ReferenceError: Cannot access `count` before initialization console.log(count); const count = 5;
The value of a variable declared with const cannot be reassigned after initialization.
const count = 110; // count = 120; // Error: Assignment to a constant variable
However, if the variable is an object or an array, the properties or elements of the object or array can be modified.
Variables declared with const must be initialized at the time of declaration. Otherwise, we encounter an error "SyntaxError: Missing initializer in const declaration"
const firstname; // it will through error firstname = "Alice";
Choosing between "let" and "const" depends on whether we want to reassign the variable's value.
If the value remains "constant", use "const" keyword Otherwise, use "let" keyword when we anticipate reassigning the variable.
"var" is generally less favoured in modern JavaScript due to its function-scoping and hoisting behaviour.
It is recommended to use "let" or "const" for more predictable and manageable code.