JS closure-module scope | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 10

JS closure-module scope

I saw this code in JS challenges: (function() { let a = b = 3; })(); console.log(typeof a == 'undefined'); console.log(typeof b == 'number'); The output is: true true How is it possible that 'b' is defined and 'a' is not defined?

16th Jan 2020, 3:01 PM
SergeiRom
5 Answers
+ 6
Since both a and b are defined within the enclosing scope of the function, and since the line they are on begins with the let keyword, most JavaScript developers would expect typeof a and typeof b to both be undefined in the above statement let a = b = 3; to be shorthand for: let b = 3; let a = b; But in fact, let a = b = 3; is actually shorthand for: b = 3; let a = b; Well, since the statement let a = b = 3; is shorthand for the statements b = 3; and let a = b;, b ends up being a global variable (since it is not preceded by the var keyword) and is therefore still in scope even outside of the enclosing function.
16th Jan 2020, 3:31 PM
DishaAhuja
DishaAhuja - avatar
+ 6
Thank you all very much.
16th Jan 2020, 4:02 PM
SergeiRom
+ 5
variable "a" is declared (with the keyword "let") inside the (anonymous) function scope, and so is not available in the global scope (where console.log is executed). variable "b" is not explicitly declared in any scope (global nor function), so it's implicitly defined in the global scope, and is available when the last "console.log" is executed...
16th Jan 2020, 3:23 PM
visph
visph - avatar
+ 3
It's easy to understand why a is undefined since a declared in closure, it's not available in global scope. For b variable, we can study let a = b = 3; is equivalent to let a = (b = 3); is also equivalent to let a= 3; b = 3; For a variable without declaration with var/let, it becomes global irrespective of where it is. Since b is global thus typeof b is number even outside of closure.
16th Jan 2020, 3:45 PM
Calviղ
Calviղ - avatar
+ 1
If "a" imply "b" and that "a" is true, so "b" is true. Like : (P & (P-->Q) ) --> Q
17th Jan 2020, 5:09 PM
yadcubox
yadcubox - avatar