+ 5

Javascript challenge question doubt

var foo1 = function(){ console.log("a"); }() var foo2 = function(){ console.log("a"); } var foo3 = function(){ foo2(); } if(foo1) foo3; console.log(typeof foo1); what is that () means in line 3 , and why foo1 is undefined https://code.sololearn.com/Wch8fZQTade4

27th Feb 2018, 9:22 PM
Morpheus
Morpheus - avatar
8 Answers
+ 13
@Morpheus on line 1 it's an expression, and you can do this. But when we write smth like: function foo () { lalala; } It's a statement, and if you put here "()", then syntax error occur.
27th Feb 2018, 9:38 PM
Vladislav Tikhiy (SILENT)
Vladislav Tikhiy (SILENT) - avatar
+ 11
foo1 is undefined because function on line 1 returns nothing (you call in on line 3 using "()")
27th Feb 2018, 9:30 PM
Vladislav Tikhiy (SILENT)
Vladislav Tikhiy (SILENT) - avatar
+ 9
@Morpheus you're welcome.
27th Feb 2018, 9:42 PM
Vladislav Tikhiy (SILENT)
Vladislav Tikhiy (SILENT) - avatar
+ 9
@Morpheus yes, it's a really good thing, in the global scope will be exist only these variables that we want.
27th Feb 2018, 9:58 PM
Vladislav Tikhiy (SILENT)
Vladislav Tikhiy (SILENT) - avatar
+ 6
im not a js expert but: - these () mean "call the anonym function" and for this that "a" be printed - foo3 is undefined because it assume return value of anonymous function call (the dont returning nothing for js rule return undefined automatically)
27th Feb 2018, 9:30 PM
KrOW
KrOW - avatar
+ 6
I would only use it to self invoke functions 😅, looks like it serves bigger purpose Burey puts question like this in challenges for a purpose, its serving me now
27th Feb 2018, 9:54 PM
Morpheus
Morpheus - avatar
+ 5
@silent got it , thx
27th Feb 2018, 9:41 PM
Morpheus
Morpheus - avatar
+ 5
I couldn't understand what's the use of it, but got some ideas from its use in the module pattern. https://toddmotto.com/mastering-the-module-pattern/
27th Feb 2018, 9:53 PM
Morpheus
Morpheus - avatar