Skip to main content


Showing posts with the label var

What is hoisting in Javascript

One of the most important and little confusing topic in Javascript is Hoisting. The literal meaning of the word ' hoisting ' is ' raising up ' and its meaning w.r.t Javascript also remains the same. Before the execution of Javascript program/file/function, it is parsed by the Javascript engine(e.g. V8 engine in Chrome). During this parsing phase, all the declaration(variable and function) gets hoisted. This mean the memory is allocatted for these variables and functions during the parsing phase. Basically its a default behaviour of Javascript engine to move all the declaration to the top of that function scope in which it is defined . Variable hoisting Since variable declaration are moved on top of the function scope, we don't get error(but undefined value) when we try to fetch a variable before its declaration. e.g. 1.   console.log(num);    // undefined 2.   var num = 5; Here, num defined in line 2 but because of hoisting its declaration is moved on to

Difference between var, let and const

   var, let and const in Javascript        Variable can be declared in three ways: var let const var  variables are function-wide scoped. Let's understand this with an example,    if(true){           var x = 5;    // variable declared with "var"          console.log(x);  // x will be 5    }  console.log(x); // even here, x will be 5          So in the last example we can see variable "x" is available outside the "if" block, that means the scope of variable with "var" is not block scope. let see with another example, 1.  function helloWorld(){       var x = 5;        2.     function abc(){              3.        console.log(x);      // even x will be 5        4.     }        5.     abc();        6.     console.log(x);  // x will be 5 7. } 8. helloWorld();              So in this example, we can see the variable "x" is available throughout the function in which it is declared. One of th