back to all posts

YDKJS — Scopes and Closures — Part2

by Nabendu Biswas / June 10th, 2018

#javascript #beginners #webdev
Series: YDKJS

Welcome to the Part2 of YDKJS series. 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.


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.

read write exampleread 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.

Let’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.

read operationread 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.

write opertionwrite 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.

Window 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.

firefox scratchpadfirefox scratchpad

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

Window objectWindow object

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

window object propertieswindow object properties

Nabendu Biswas