+ 6

function (x, f = () => x) 👈 What's exactly happening hereâ‰ïžđŸ€”

Could somebody please explain the condition for the function and the return expression in the attached code? And why's the output 4 and how does the (1) after the function has ended relate to var r? 😅 Thanks. 😁 https://code.sololearn.com/WeX6nGsJIKq8/?ref=app

15th Apr 2018, 6:14 PM
Miro
Miro - avatar
3 RĂ©ponses
+ 6
its quite complex: var r = (function (x, f = () => x) { var x; var y = x; x = 2; return (x + y + f()); })(1) console.log(r); it accepts two parameters: x and a function f which returns x. so when 1 is passed as the parameter. var y=x so y is 1 then the value of x is changed to 2 so.. x is 2 and function f which returns x so f() is 1.why?f() returns parameter x not the x declared in function so x+y+f() is.. 2+1+1=4
15th Apr 2018, 6:36 PM
᠌᠌Code X
᠌᠌Code X - avatar
+ 3
Hi Miro the only thing to add to Brain's answer is that this is also known as an IIFE. An Immediatly Invoked Function Expression. Which is why you see the parenthesis around the whole function. The statement gets executed as soon as it is assigned. The fat arrow function declaration f=()=>X is ES6 notation for function declaration. IIFEs are normally used to declare bindings of functions and variables that you want to keep out of the global scope, though the example is not a very good case of this. Typical interview type question.
15th Apr 2018, 10:33 PM
Mike Choy
Mike Choy - avatar
+ 2
This is called Arrow Function Expression. Some people call them “fat arrow” functions. These functions cannot be used as constructors.
16th Apr 2018, 1:00 PM
Bill Zelenko
Bill Zelenko - avatar