Tricky Parts of JavaScript [Part 3]

in #javascript6 years ago (edited)

Welcome to the 3rd part of JavaScript Tricky Part. In this post we will be seeing some functions and hoisting related stuff.. These posts are to teach you the basic functioning of JavaScript so that you can tackle any complicated problem in future. Here we begin...


Q1. What will be the output of code below?

var a = "funnyman"



(function() {



 console.log("Value of a = " + a)



 var a = "steemit"



 console.log("Value of version2 a  = " + a)



})()




Ans: The output of the above code execution will be as 

Value of a = undefined

Value of version2 a  =  steemit

So why the value in the first log is undefined? Well the answer is hoisting which moves all the variable declarations to the top of the function where these  are defined. So the above code executes as:


var a = "funnyman"



(function() {

 var a = undefined  // Hoisting in action.

 console.log("Value of a = " + a)



 a = "steemit" // Notice here



 console.log("Value of version2 a  = " + a)



})()




Q2. What is the difference between the following function declarations?

1. var a = function() {}
2. function a() {}

Ans: The main difference between these declarations is the first one is defined at the runtime and the second one at parse time.  That is why in case of second function calling it before the function declarations works whereas it doesn't in case of the first one.

a(); // This will work without any error.

function a() {}
a(); // It is going to throw error.

var a = function() {}


Q3. What is the going to be the output of the following code?

var i = 10;

var j = i = typeof j

console.log(j)


Ans: Well, this is a tricky one. In order to answer this question you will need to into a bit depth how the parsing works and what is associativity. I am not going to explain about these but just a brief overview. It defined how our operators and variables are processed. In our case it will be processed From Right to Left . So with that first typeof will be evaluated which is undefined which will be assigned to i and then to j . And hence the value of j is undefined


More CONTENT to COME...STAY TUNED

@funnyman

Sort:  

Great post as always. I love it.

Let me know if you need any help

Thanks man

Thanks

Thank you for reading

Thanks for coming by

Please share

Thanks again

Glad to post it

Cool

@funnyman You have earned a random upvote from @botreporter & @bycoleman because this post did not use any bidbots.

Thanks

So i am learning a new language .. Thankyou

Coin Marketplace

STEEM 0.37
TRX 0.12
JST 0.040
BTC 70162.45
ETH 3540.43
USDT 1.00
SBD 4.79