+ 3

Why is the output of this 4? Could someone be kind enough to explain?

var r = (function (x, f = () => x) { var x; var y = x; X = 2; return (x + y + f() ); }) console.log (r)

8th Apr 2018, 2:38 PM
Levi
Levi - avatar
6 Respuestas
+ 6
You are probably missing something. This code won't output 4 but will print the function r.
8th Apr 2018, 3:36 PM
Swapnil Srivastava
Swapnil Srivastava - avatar
+ 6
Important thing to note on this code is that the function f = () => x on second argument, operates on the x value that is in the arguments and not inside the function where x = 2 so f() will always return that value that is passed as the argument to x in the IIFE
8th Apr 2018, 6:06 PM
Morpheus
Morpheus - avatar
+ 5
var r = ( function(){ // code })(1); is a immediately invoked function expression IIFE , and in IIFE we can pass the argument to the function by the outer () like (1) , so 1st argument x is passed value 1 in next argument f = () => x we define a function based on argument x in es6 arrow notation , which simplifies to this var f = function (){ return x ; } so doing f() later returns the passed arg value of x Also note that final value at r depends on what is returned inside the IIFE, return ( x + y + f() ) ; breaks down to return ( 2 + 1 + 1); // 4
8th Apr 2018, 5:53 PM
Morpheus
Morpheus - avatar
+ 4
Ahhhh... I see. That was a really thoughtful response, thank you. This is the first I am hearing about IIFEs and arrow notations. I will have to study them in more depth but really appreciate the explanation. Helps a great deal.
8th Apr 2018, 6:17 PM
Levi
Levi - avatar
+ 3
as Swapnil said , but here are few modifications to produce 4, you must be missing something, and this one might be different var r = (function (x, f = () => x) { var x; var y = x; x = 2; return (x + y + f() ); })(1); console.log (r)
8th Apr 2018, 3:58 PM
Morpheus
Morpheus - avatar
+ 3
Yes Morpheus, you are very correct. I forgot the (1) at the end. But still not understanding how it outputs 4?
8th Apr 2018, 5:37 PM
Levi
Levi - avatar