Skip to main content

Command Palette

Search for a command to run...

Variables in JavaScript

Updated
•3 min read•View as Markdown
Variables in JavaScript

A VARIABLE IS A " NAMED STORAGE " FOR DATA .

Declaration :- In JavaScript variables can be declared using

  1. let

  2. const &

  3. var

let and const were introduced in 2015 ( ES6 )

var :

it is function ( if declared inside a function ) or Global scoped ( if declared globally ) . it allows variable to be both Re-assigned and re-defined . Allows Hoisting .

scope : Function . Re-assignable : Yes . Mutable : Yes . Temporal dead zone : No .

let :

Block scoped . Allows Reassignment .

scope : Block . Re-assignable : Yes . Mutable : Yes . Temporal dead zone : Yes .

const :

used to declare constant . Once a value is assigned to a constant using const , it cannot be changed or reassigned throughout the execution of the script . it is important to note that if the value is in the form of array or object , its elements or properties can still be modified .

scope : Block . Re-assignable : No . Mutable : Yes . Temporal dead zone : Yes .

Hoisting :

var declarations , wherever they occur in a script , are processed before any code within the script is executed . Declaring a variable anywhere in the code is equivalent to declaring it at the top ( in its block ) . this also means that a variable can appear to be used before it is declared . this behaviour is called HOISTING .

[ if we try to access var declared variable before their declaration we get undefined , not an error . But in case of let and const , if we try to access them before their declaration we get a reference error , this is known as Temporal dead zone . ]

Scope :

The context in which values and expressions are 'visible' or can be referenced . if a variable or other expression is not 'in the current scope' then it is unavailable for use .

Variable mutation :

A variable is said to have been mutated when its initial value has been changed afterward . A variable is said to be immutable if it can't be mutated .

Summary : -

Featurevarletconst
ScopeFunction scope or global scopeBlock scopeBlock scope
HoistingHoisted and initialized as undefinedHoisted but not initialized (TDZ)Hoisted but not initialized (TDZ)
Re-declarationAllowed in the same scopeNot allowed in the same scopeNot allowed in the same scope
Re-assignmentAllowedAllowedNot allowed
InitializationCan be declared without initializationCan be declared without initializationMust be initialized at declaration
Temporal Dead Zone (TDZ)NoYesYes