JS closure-module scope | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
+ 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 Respostas
+ 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