0

I am new to programming and javascript. I am having a confusion in the output of below code.

So here in the 1st code, the output is 10 and in 2nd code, the output is 20 how?

var a = 10;

function test() {
    a = 20;
   return;
   function a(){}
}

test();
console.log(a);

var a = 10;

function test() {
    a = 20;
   return;
   
}

test();
console.log(a);
Jared Smith
  • 19,721
  • 5
  • 45
  • 83
  • It is due to hoisting. In the first snippet you redefine a as a function so it goes on top o a=20. Then you assign 20 to a that is a function. Hope it is clear. To understand better add console.log(a); in the first snippet before and after assignin value 20 – hpfs Aug 21 '20 at 07:05
  • the second is easy to explain. when yo execute `test` you assign 20 to a, first it searches inside his execution context for this variable. it doesnt find it so it goes 1 layer up and searches there for an variable called `a` and find it, and assign 20 to it. but in the first one: your function a gets hoisted inside his executiong context. you can imagine it like putting the function `a` before your variable `a`. now you assign 10 to `a` and same happens here. it first searches inside the function if there is an `a` in this case it is. its the function because its hoisted – bill.gates Aug 21 '20 at 07:25
  • @hpfs var a = 10; function test() { function a(){} console.log(a); a = 20; return; } test(); console.log(a); now when I am trying to console first it is printing the function and then the value 10 – Kirti Sharma Aug 21 '20 at 15:24

0 Answers0