Showing posts with label JavaScript Hoisting. Show all posts
Showing posts with label JavaScript Hoisting. Show all posts

Tuesday, December 6, 2016

JavaScript Function context - Q&A

Question:

What is the result of the following code? Explain your answer. 



Answer

The code prints Aurelio De Rosa and John Doe. The reason is that the context of a function, what is referred with the this keyword, in JavaScript depends on how a function is invoked, not how it’s defined. In the first console.log() call, getFullname() is invoked as a function of the obj.prop object. So, the context refers to the latter and the function returns the fullname property of this object. On the contrary, when getFullname() is assigned to the test variable, the context refers to the global object (window). This happens because test is implicitly set as a property of the global object. For this reason, the function returns the value of a property called fullname of window, which in this case is the one the code set in the first line of the snippet.



JavaScript hoisting - Q&A

Question:

What’s the result of executing this code and why?










Answer

The reason is that both variables and functions are hoisted (moved at the top of the function) but variables don’t retain any assigned value. So, at the time the variable a is printed, it exists in the function (it’s declared) but it’s still undefined. Stated in other words, the code above is equivalent to the following:



JavaScript hoisting - Q&A

Question:

Please describe what will be printed out to the screen and why?




Answer

Undefined.
In one word, Hoisting. Hoisting is JavaScript's default behavior of moving all declarations to the top of the current script or the current function. Important to note that JavaScript only hoists declarations, not initializations. Because of Hoisting the code above will actually look like this;