What's the result of executing this code and why. 1 2 3 4 5 6 7 8 9 10 11 function test() { console.log(a); console.log(foo()); var a = 1; function foo() { return 2; } } test();

Answer

The result of this code is undefined and 2.

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
function test() {
   var a;
   function foo() {
      return 2;
   }
 
   console.log(a);
   console.log(foo());
    
   a = 1;
}
 
test();

All javascript Questions

Ask your interview questions on javascript

Write Your comment or Questions if you want the answers on javascript from javascript Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---