This is my third post in the series - "Perplexed world of javascript" . It is very important and subtle concept , hence i will try to explain in a very intuitive way.
So i guess most of you must have been in relationship.Now what is the difference between "Breakup" and "Moving On"?
"Beakup" is an event and it is very visible and evident but not the "Moving On" , it is a very subtle in nature and it depends on people how many months , years or even decade ,it will take to completely "Move On".Now programming languages also behave in similar manner.
Lets try to figure out the output of the following code snippet.
//Code Snippet
function a () {
var x=11;
var b=function () {
alert(++x);
} ;
return b;
}
var funB=a();
//call 1
funB();
//call 2
funB();
If you think both "call1" and "call2" both will return 12, then you are a person who believes "Breakup" and "Moving On" both occurs at a time and yes one more thing you are coming from a "JAVA" or "C++" background. In these languages end of a function marks the end of its scope too.
Javascript is a sensitive language :) It takes time to "Move On" means to say the end of the function does not mark the end of its scope.
If there are variables declared inside a function (like x) and also some internal functions are defined (like b). The internal functions (like b) will have its own copy of the internal variable (like x) even after the end of the parent function.
Hence the output will be 12 and 13 in this case.When we made "call1" ,"x" becomes 12 and "call2" made the value of "x" 13. Now if we get a new copy of function "b" by invoking function "a" then again this new copy will get a fresh copy of "x" i.e 11.
If you have any question please shot out here.I will be more than happy to help.
Happy coding to all of you.
This type of programming makes javascript confusing for many developers. But there is real pleasure in cracking this code. Good one dude.
ReplyDeletem a beginner in this language and want to ask a very basic question...
ReplyDeleteHow to run the snippets and see the O/P? :P
1. Open a text editor.
Delete2. Write code as i have shown in the image above in the post.
3. Put your javascript at the place marked as "//Paste any javascript code here//".
4. Save the file with the extension ".html" e.g Test.html.
5.OPen in your favorite browser.
6. Voila :) you just executed your first javascript.