Javascript

Var vs Let vs Const in JavaScript

In this topic we will learn:

var’ keyword.

Variable Hoisting

Problems with ‘var’ keyword

let’ keyword.

const’ keyword.

var  vs let  vs const

Scope

Scope decide where the variable is available for use. JavaScript have 3 Scopes:

•Global

•Function/Local

•Block

var Keyword

Before ES6 Edition, ‘var’ keyword  ruled the variable declarations.

However, there are issues associated to variables declared with ‘var’.

Scope of var

var is function scoped when it is declared within a function. This means that it is available and can be accessed only within that function.

var variable declared outside a function have a global scope and is available to use in whole window.

var variables can be redeclared and updated

let keyword

With ES6 edition new keywords let and constwere made available to declare variables.

Scopeof let:

A block is a chunk of code bounded by {}. Anything within curly braces is a block.

A variable declared in a block with let  is only available for use within that block.

let can be updated but not re-declared.

let a better choice than var.

When using let, you don’t have to bother if you have used a name for a variable before as a variable exists only within its scope.

const keyword

JavaScript const variables must be assigned a value when they are declared, and they maintain constant values.

Scopeof Const

A variable declared in a block with const  is only available for use within that block

const cannot be updated or re-declared.

While a const object cannot be updated, the properties of this objects can be updated.

Var vs Let vs Const

Please check below video for more detailed explaination on Var vs Let vs Const in JavaScript:

Let me know if you have any questions in the comment section of the video.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s