What is the difference between var and let #Javascript


The main difference between var and let is scoping rules.

Variables declared by var keyword are scoped to the immediate function body (hence the function scope) while let variables are scoped to the immediate enclosing block denoted by { } (hence the block scope)

ECMAScript 6 introduced the let keyword as the solution for the issues arrived with var keyword

Diff #1 Block level scope

Here in below example we have created variables with var and let and both are accessible inside the block but only variable declared with var is accessible outside.

Diff #2 Creating global object property

let, does not create a property on the global object

var, creates a property on the global object

Diff #3 Hoisting

Variables declared with var keyword are hoisted (initialized with undefined before the code is run) which means they are accessible in their enclosing scope even before they are declared

Variables let are not initialized until their definition is evaluated. Accessing them before the initialization results in a ReferenceError. Variable said to be in “temporal dead zone” from the start of the block until the initialization is processed

Diff #4 Redeclaration

var will let you re-declare the same variable in the same scope in strict mode but let raises a SyntaxError.

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