Hoisting
This is another weird part of Java script. Some times this is misleading and useful at times. Let us take an example below.
1
2
3
| console.log(myvar); //undefined
var myvar ='Hello World!';
console.log(myvar); //Hello word!
|
In most of the programming languages line 1 will result in an error saying variable not declared. But in Java Script it didn't throw an error. if we assume that without var keyword variable got created then second line should result in error saying variable already declared. Neither of them happened.
What is happened?
Hoisting is happened. Hoisting is not an ECMA terminology. Execution in Java script engine is happens in two phases.
Creation
On creation phase all variable and functions will get allocated memory. By default variables will get assigned with undefined. This creation phase is mostly misinterpreted as hoisting.
Execution
In Execution phase only code will be get executed line by line. Execution is like any other programming languages will be executed line by line.
Here is what happened.
On creation phase myvar variable is got created and assigned with undefined. On execution phase, first line printed undefined, on second line myvar will get assigned with "Hello world!". In third line it printed with "Hello world!".
Conclusion
Hoisting is nothing but allocation memory to variables and functions even before the execution of line of code.To avoid confusion declare variables at the top of the function.
No comments:
Post a Comment