In JavaScript, let
, const
, and var
are used to declare variables, but they have some differences in terms of their behaviour and scope.
Var
var
was traditionally used to declare variables in JavaScript. It has function scope, which means that if a variable is declared inside a function, it is only accessible within that function. If a variable is declared outside a function, it becomes a global variable, which can be accessed from anywhere in the code. One of the drawbacks of var
is that it allows you to declare the same variable multiple times within the same scope, which can lead to unexpected behaviour.
Example 1: if a variable is declared with `var` inside a function, it is only accessible within that function.
function sum(){
var result= 20;
console.log(result); //20
}
console.log(result) //undefined
sum();
Example 2: If a variable is declared with var
outside a function, it becomes a global variable, which can be accessed from anywhere in the code.
var result= 20;
function sum(){
console.log(result); //20
}
console.log(result) //20
sum();
Let and Const
let
and const
have block scope, which means that if a variable is declared inside a block (a set of curly braces), it is only accessible within that block. This helps prevent variable name collisions and unintended variable sharing. The difference between let
and const
is that let
variables can be reassigned, while const
variables cannot be reassigned.
let count = 0; // declare a variable with let and global variable with Let
let result = 55; // global variable with Let
if (true) {
console.log(result); // logs 55
let count = 1; // declare another variable with let inside a block
console.log(count); // logs 1
}
console.log(count); // logs 0
count = 1;
console.log(count); // logs 1
console.log(result); // logs 55
const PI = 3.14159; // declare a constant with const
PI = 3.14; // throws an error because PI is a constant and cannot be reassigned