`let` vs `var` – Part 1

Cover image courtesy – here.

This series of posts is aimed at preparing oneself to face JavaScript technical interviews. Here is the source code.

In this post, I shall talk about let vs var, scoping, and hoisting of JavaScript variables.

let vs var

The main difference between let vs var is that they have block vs function scope respectively.

What is scope?

Scope is a set of rules for looking up variables by their identifier name.

In simpler words, scope determines visibility for variables.

Simple example:

 

Screen Shot 2018-01-11 at 20.12.30

In the first case, there is a ReferenceError, because the variable tmp is declared outside the scope of the executing code.

Declaration vs Definition of a variable

var tmp Here, the variable tmp is only declared. It isn’t defined, i.e. it isn’t assigned any value.

var tmp = 123 The variable tmp is both declared and defined here.

Variable defined, but not declared

All undeclared variables in JavaScript are global variables.

Screen Shot 2018-01-11 at 21.14.45

ReferenceError vs undefined

Screen Shot 2018-01-11 at 20.46.20

Variable hoist is undeclared, but notice the text for ReferenceError in the above message – hoist is not defined! Think of opening a PR to one of the browser JS engines to fix this message?!

Hoisting

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.

Variable hoist is hoisted in the above code snippet and therefore logs undefined. In case of hoisting, this is how the JavaScript interpreter sees the code:

Screen Shot 2018-01-11 at 21.24.56

Temporal Dead Zone

A variable declared by let has a temporal dead zone (TDZ). When entering its scope, it cannot be accessed until the execution reaches its declaration.

In simpler words, let variables aren’t hoisted!

let vs var in loops

A var in the head of a for loop creates a single storage space for that variable.

In a let, a new storage space is created for each iteration of the loop.

Screen Shot 2018-01-11 at 22.05.23.png

The next time, someone asks you SCOPE, these are the things to keep in mind!

Source code for all the above code snippets is here.

 

Advertisements

2 thoughts on “`let` vs `var` – Part 1

Add yours

  1. Excellent weblog here! Also your site lots up fast! What host are you the use of? Can I get your affiliate link for your host? I wish my site loaded up as fast as yours lol

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: