Skip to main content


Showing posts with the label hoisting

Javascript Hoisting Interview Question and Answers - 5

In this post,I have tried to cover all the types of possible interview questions and answers on hoisting. If you are not familiar with the hoisting, I would highly recommend you to go to my post on hoisting . Once you are comfortable with the topic, you can attempt these questions. Understanding the type of question will help you to answer. I have provided the hint after each question. All the answers are given at the end of the post. //Question 1 console.log('bar:', bar) bar = 15 var foo = 1 console.log(foo, bar) var bar Hint : Basics of hoisting //Question 2 var foo = 5 console.log('foo:', foo) var foo; var bar = 10; var bar; console.log('bar:', bar) var baz = 10 var baz = 12 console.log('baz:', baz) Hint : Basics of hoisting     //Question 3 function foo() { function bar() { return 5 } return bar() function bar() { return 10 } } console.log(foo()); Hi

Come Closure in Javascript

What is a closure? If we want to derive a definition,we can say, A closure is a feature of Javascript where inner function has access to the outer (enclosing) function’s variables—scope chain. This scope chains means inner function has: access to its own scope (variables defined between its curly brackets and its parameters), access to the outer function’s variables and parameters,  access to the global variables. Now we will look into it in detail. Consider following example var globalVar = "xyz"; function outerFunc(outerArg) { var outerVar = 'Alex'; function innerFunc(innerArg) { var innerVar = 'Chris'; console.log("globalVar = " + globalVar); console.log("outerArg = " + outerArg); console.log("innerArg = " + innerArg); console.log("outerVar = " + outerVar); console.log("innerVar = " + innerVar); } innerFunc(456); } outerFunc(12

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