+ 1

Can someone explain what is happening in this code JS

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

30th Jul 2018, 1:00 PM
Cлaвeн Ђервида
Cлaвeн Ђервида - avatar
2 Réponses
+ 2
First, you need a semicolon ";" between "(1)" and "console.log(r)" if you keep them on same line, else you got an error: js provide automatic semicolon insertion at end of lines (when a break line character occurs), but not between two statements... The last statement "console.log(r)" simply output the value assigned in the first statement to the variable "r". The first statement declare ("var") and assign a value to the variable "r", using an anonymous (without name) IIFE ( Immediatly Invoked Function Expression) wich take two arguments, "x" and "f", and where the first one is provided at the end of the function definition in the invocation parentheses (1) and the second one get a default value as an anonymous "arrow" function. Basically, an arrow function is a shorthand function declaration (there's much more details wich cause it to be sligtly different in reality, but most of the time that's equivalent ): var f = () => x; ...is almost same as: function f() { return x; } In the IIFE body, the first statement "var x" is unnecessary, as "x" is already implicitly defined in the function scope in the arguments scope. Anyway, by declaring it, you define another variable wich will be used instead of the "x" attribute when assigning a new value (result is different if you remove it). Then another variable "y" is declared and assigned with the value of "x", wich at this time is still undefined in the function scope, so the "x" value of arguments scope is used, and finaly "x" in the function scope get the value of 2 (but "x" in the arguments scope stay unchanged, so calling the function f() will still return the argument value because was defined in this scope). So the computed returned value is (x + y +f()) == (2 + 1 + 1) == 4 And without the "var x" declaration, the final value would be (2 + 1 + 2) == 5 https://en.m.wikipedia.org/wiki/Immediately-invoked_function_expression https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
30th Jul 2018, 11:44 PM
visph
visph - avatar
0
thank you so much for help
30th Jul 2018, 11:46 PM
Cлaвeн Ђервида
Cлaвeн Ђервида - avatar