JavaScript - Types of Variables

JavaScript – Types of Variables

For a very long time, var was the only way to create variables in JavaScript. ECMAScript 2015 introduced two new methods to create variables: let and const. Before we jump into differences, let’s get to know about a few things:

  1. Declaration
  2. Initialization
  3. Assignment
  4. Scope

DECLARATION: In programming construct, declaration is the process of specifying properties of an identifier. These properties can include data type, scope etc. 

INITIALIZATION: Initialization is the process of assigning initial value to the variable.

ASSIGNMENT: Assignment is the process of assigning a value in the variable.

SCOPE: Scope simply refers to the visibility of a variable. The parts of the program which can see and use the variable.

Now, let’s get into the business

VAR:

var is the oldest method of declaring variables in JavaScript. So, var is function scoped and it is initialized with undefined; and it is hoisted. Which means using a variable before declaration is perfectly valid.

LET:

let was introduced in ES 2015. Let is hoisted, it is block scoped and it is not initialized with anything. Which means, it is valid to use a let declared variable to use before declaration, but using it before initializing it with value is going to throw an error.

The place where let is declared and the place where let is assigned a value is called temporal dead zone. Using that let variable in temporal dead zone is going to throw a Reference error.

CONST:

const was also introduced alongside let in ES 2015. const is also hoisted, it is block scoped, and it is mandatory to initialize manually it with value while declaring.

TLDR:

TYPESCOPEINITIALIZATIONHOISTED?
varFunctionundefinedYes
letblockTemporal Dead ZoneYes
constblockMandatory to Assign ValueYes

Posted

in

by