what is var, let and const?
var
:var
is the oldest way to declare variables in JavaScript.Variables declared with
var
have function scope, meaning they are accessible within the function they are declared in.If
var
is declared outside any function, it has global scope and can be accessed from anywhere in the script.var
does not have block scope, so variables declared withvar
are accessible even outside the block they are defined in.var
allows you to redeclare and reassign variables multiple times throughout the code, which can lead to unexpected behavior and bugs if not used carefully.
let
:let
is a newer way to declare variables introduced in modern JavaScript (ES6).Variables declared with
let
have block scope, meaning they are limited to the block of code they are defined in (e.g., within loops or conditional statements).Variables declared with
let
can be reassigned within their scope.Unlike
var
,let
does not allow the redeclaration of the same variable within the same scope, which can help prevent accidental errors and conflicts in your code.let
:let
is a newer way to declare variables introduced in modern JavaScript (ES6).Variables declared with
let
have block scope, meaning they are limited to the block of code they are defined in (e.g., within loops or conditional statements).Variables declared with
let
can be reassigned within their scope.Unlike
var
,let
does not allow the redeclaration of the same variable within the same scope, which can help prevent accidental errors and conflicts in your code.
const
:const
is also introduced in modern JavaScript (ES6).Variables declared with
const
also have block scope.const
stands for "constant" and is used to declare variables that should remain unchanged after being assigned a value.const
variables are read-only and cannot be reassigned once defined.While the variable itself cannot be reassigned, if the value is an object or an array, its properties or elements can still be modified.
In short
Var is globally scoped while let and const are block scoped.
var can be updated & redeclared within its scope.
let can be updated but not redeclared.
const can neither be updated nor be redeclared.
var variables are initialized with undefined where as let and const variables are not initialized.
const must be initialized during declaration unlike let and var.