+3

Javascript function return

function abc(a) { return (function(y) { return y + 1; }) (++a) + a } document.write(abc(2)) The output is 7 but I don't understand two things below: 1. 'return' part comes first even though it should be placed in the end; because it stops func execution. When I put '(++a) + a' in the beginning and 'return' part in the end of the func block, however, it doesn't work properly. 2. Based on the output, it seems that '(++a) + a' is assigned to y parameter. But why? Please someone help me grasp the whole flow of this code. Thanks in advance.

1/22/2020 5:28:02 AM

Solid State

6 Answers

New Answer

+8

This questions involves two JavaScript concepts: IIFE and ASI. Firstly, function(y){return y + 1;} itself is a function, when you wrap them with parenthesis, you are going to add another parenthesis to execute it. (function(y){return y +1;})(4) will be the same as function addOne(y){ return y+1; } addOne(4); that's the immediately-invoked function expression part. 2. for ending a line at }), as explained above, because it is IIFE, the compiler do not perform automatic semicolon insertion here; instead of ASI, it append the next line to the current line. 3. So the execution is return addOne(++a) + a. So noted that you are wrong in that the + a part also put into as y, actually only the (++a) because it is in parenthesis. 4. the variables changes a is 2, ++a is executed, a becomes 3, y is 3, 4 is returned, a is 3 now, so (4) + 3, so result is 7. 5. To Rai, Kuba's explanation is wrong.

+8

Gordon Masterfully and thoroughly answered. I can't find one thing wrong with your various points. I only wanted to add a link to a fantastic article I found a few years ago regarding ASI in Javascript. https://2ality.com/2011/05/semicolon-insertion.html

+2

//In short it working like this //example code like above ((name)=>{ this.user = name console.log(user+'doe') })('john') //Please see this thread similar already answered https://www.sololearn.com/Discuss/1756451/function-abc-a-return-function-y-return-y-1-a-a-alert-abc-2 https://www.sololearn.com/Discuss/482453/?ref=app

+2

The function in parentasis is an anonmymous function called with argument (++a). The return value of this function is then added to a. You can do a separate function for the nested function and name it for exemple "myFunction". The final result would look more clear : function abc(a) { return myFunction(++a) + a; }

+1

Thanks, Gordon. You're the best.

-1

what have you written...?!😱