The variables are declared in JS using three keywords:
var
: Older way to declare variables.let
: It allows for block-scoping and is commonly used for mutable variables.const
: It declares a constant variable whose value cannot be re-assigned. It's commonly used for immutable values.let, const are preferred as they provide better scoping
Example:
// Using var
var age = 19;
// Using let
let name = "DevDuo";
// Using const
const PI = 3.14;
let globalVar = "I am global";
function exampleFunction() {
console.log(globalVar); // Accessible inside the function
}
exampleFunction();
console.log(globalVar); // Accessible outside the function
function localExample() {
let localVar = "I am local";
console.log(localVar); // Accessible inside the function
}
localExample();
// console.log(localVar); // This would result in an error; localVar is not accessible outside the function
let
and const
are block-scoped, meaning they are only accessible within the block (enclosed by curly braces) where they are declared.if (true) {
let blockVar = "I am block-scoped";
console.log(blockVar); // Accessible inside the block
}
// console.log(blockVar); // This would result in an error; blockVar is not accessible outside the block