Although JavaScript is an 0bject-orientic language, it is not the same as other OOP language like Java in some aspects. Hence, understanding the underlying principles of JavaScript is crucial for a web developer. Today we will go through some of the traps that functions and closures can pose, with pieces of example code. function testVar(){ var x = 5; console.log('first x is '+ x);//expected output 5 if (x == 5){ var x = 6; console.log('second x is '+ x);// expected output 6 } console.log('third x is '+ x);// expected output 6 } testVar(); In this function, x was declared as 5 at the very beginning so there is no doubt that it would be output as 5 in line 3. In the condition statement, x is replaced with 6 becasue it meet the condition hence the second x is 6. Again, line 8 will output 6 because x has already been changed when it runs outside of the statement. Now let's inspect the second example.


I guess you came to this post by searching similar kind of issues in any of the search engine and hope that this resolved your problem. If you find this tips useful, just drop a line below and share the link to others and who knows they might find it useful too.

Stay tuned to my blogtwitter or facebook to read more articles, tutorials, news, tips & tricks on various technology fields. Also Subscribe to our Newsletter with your Email ID to keep you updated on latest posts. We will send newsletter to your registered email address. We will not share your email address to anybody as we respect privacy.


This article is related to


javascript,web dev,functions,closures,object oriented language