-4

This is the code I am compiling.

var a = 10;
var c = 5;
b(40);

function b(x) {
  a(20);
  a=40;
  c=50;
  function a() { console.log(x);}  
}

console.log(a);
console.log(c);

Can you tell me the output and explain it?

  • 3
    This sounds like an assignment, which afaik shouldn't really be asked directly on SO. If you elaborate a bit, explain which parts you do and don't get, and maybe add a more specific question I'm sure people would be more willing to help :) – Luca_Scorpion Jan 20 '21 at 11:39
  • @Luca_Scorpion maybe he wants to ask why it's 40 10 50 and not 40 40 50? –  Jan 20 '21 at 12:00
  • 1
    @bestPlayer_xu Maybe? But that's exactly my point, the question is too vague to give a good answer imo. – Luca_Scorpion Jan 20 '21 at 12:09
  • @Luca_Scorpion Yeah. and the whole code doesn't make sense (to me) –  Jan 20 '21 at 14:19
  • @bestPlayer_xu yes that's what I'm asking. Above code giving output : 40 10 50. when I change the name of function "a", it's giving output : 40 40 50 – Ahmad Sadiq Feb 08 '21 at 10:41

2 Answers2

2

40 10 50

First b(40) will be executed. Then a(20) which will ignore the 20 and print the x (currently 40). Then a will be set to 40 and c to 50. Then both of them will be printed in line 12 and 13.

Ondolin
  • 324
  • 2
  • 13
  • but the a used in b() isn't the same as the one as in the beginning (diff vars in diff functions) –  Jan 20 '21 at 14:18
  • Above code giving output : 40 10 50. when I change the name of function "a", it's giving output : 40 40 50 – Ahmad Sadiq Feb 08 '21 at 10:42
2

40 10 50

the second one is 10 bc the a declared in b() isn't the same var as the one declared in the beginning (just execute the code).

  • Above code giving output : 40 10 50. when I change the name of function "a", it's giving output : 40 40 50 – Ahmad Sadiq Feb 08 '21 at 10:42
  • @AhmadSadiq no need to comment twice, you'll get one answer. actually, what's the issue? –  Feb 08 '21 at 15:25