Quantcast
Channel: Sankarsan's Journal
Viewing all articles
Browse latest Browse all 42

Javascript Variable Scope & Hoisting

$
0
0

In this post we will discuss about the scope of a javascript variable and how “hoisting” works in javascript. Let’s start with a simple global variable definition.

image

In this code “a” is defined as a global variable and should be accessible to all the functions.So quite naturally the function “f” will print “global” i.e. value of the global variable “a” in the console.

In the code below, we have introduced a small change and added declaration of another variable named “a” in the function “f”.

image

Here the program will give precedence to the local variable “a” and will print “local” to the console. So far it’s quite intuitive.

image

Here we are trying to access the value of “a” first followed by the local variable declaration of same name and then again printing it’s value to the console. Most of us would expect to the following in the console.

global

local

It will print the following instead:

undefined
local

This happens because the way javascript handles variable declaration and initialization.It first scans the function and finds out all the variables and declares them on top but does not initialize them. Then when the code executes it provides the initialization value in the actual line where its defined. So when the first console.log statement executes it sees that there is a variable named “a” defined but not initialized so it will print “undefined”.

This is how variable hoisting (moving to the top) works in javascript where the declarations are only hoisted and not the initialization.

So this can lead to undesirable behavior and it is safe to declare the variable at the top of the function before its use.



Viewing all articles
Browse latest Browse all 42

Trending Articles