+ 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

3 Answers

+ 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

+ 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.

+ 2

This is called Arrow Function Expression. Some people call them āfat arrowā functions. These functions cannot be used as constructors.