0

I was playing around Java script. I was expecting an output of 10 twice. Since I have declared var a = b = 10; here I struck, got error saying "a" is undefined and hiding that console.log(a); next console.log(b) gives me output as 10. I am not getting how "a" become undefined, even the console is after the function execution it must be undefined to b as well. or Is this wrong way to assign a value. Any clarification is on scenario is much appreciated.

(function(){
var a = b = 10;
})();
console.log(a);
console.log(b);

(function(){
var a = b = 10;
})();
//console.log(a);
console.log(b);
Manjula D
  • 145
  • 2
  • 8
  • 2
    `b = 10` implicitly creates a `b` property on the global object. (Bad idea - use strict mode instead.) `var a = b = 10` resolves to `var a = 10`, and `a` has only local scope inside the function, so it's not defined outside – CertainPerformance Dec 19 '19 at 08:13
  • 1
    As per your explanation, mentioned var keyword applied only to a not to b. It separates var a = b= 10 as var a=10 and b=10 ; so a becomes undefined and b has a value. am I correct @ CertainPerformance – Manjula D Dec 19 '19 at 08:20
  • 1
    Yep, that's right – CertainPerformance Dec 19 '19 at 08:21

0 Answers0