YDKJS — Scopes and Closures — Part2

Welcome to the Part2 of YDKJS series. You can find part 1 here. As told in part1 this series is based on my learnings from legendary book series You don’t know JS by Kyle Simpson and Javascript series by Kaushik Kothagul from Javabrains.

Before understanding scope in details we have to understand two concept. Every operation in JS is either Read operation or Write Operation.

Consider the below statement -

var a = 10;

Now this is a write operation because we write 10 to variable a.

Now, consider the below statement.

console.log(a);

This is a read operation because we read the value of variable a.

Let consider another example.

var a =10;
var b;
b=a;

Now in this the line b=a is interesting, because for a it’s a read operation and for b it’s a write operation.

Let consider another example to make the concept even more clear.

Image for post
Image for post
read write example

Now at line 4, there is a write operation because when greet(“Nabendu”) is called from line 8, we have function greet(name=”Nabendu”) here. So, assigning name variable the value “Nabendu”.
And at line 5 the usual read operation as we are reading the value of a.

et’s move to one more important concept related to read and write operations.

If we use a variable without declaring it. It is ok to do a write operation, but not ok to do a read operation.

Let’s see example to be more clear.

Image for post
Image for post
read operation

In the above we tried to do a read operation on a variable foo, without even declaring it and the compiler throws an error.

Now consider below.

Image for post
Image for post
write opertion

We do a write operation in line 1 ie foo=10. Here also we are not declaring foo. Now this is perfectly right and the compiler doesn’t throws an error.

indow object is the object in which all global variables are created as properties.

Let’s define these below two variables in firefox scratchpad and then do reload and run.

Image for post
Image for post
firefox scratchpad

In the firefox console write window and we can see the Window object containing these two variables.

Image for post
Image for post
Window object

Also, can access these two variables as window object’s properties.

Image for post
Image for post
window object properties

This concludes part 2 of the series. Get the part3 here.

Written by

UI Lead- ReactJS, JavaScript and everything in-between.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store