Before understanding scope in details we have to understand two concept. Every operation in JS is either Read operation or Write Operation.
Note - Scratchpad used in this series is not available anymore. You can use jsbin.com instead, to run everthing in this series.
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 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.
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.
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.
In the firefox console write window and we can see the Window object containing these two variables.
Also, can access these two variables as window object’s properties.
window object properties