Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the parenthesis missing in this anonymous function call? [duplicate]

I am reading this book and it has this code example

function getFunction() {
    var result = [];
    for (var i = 0; i < 10; i++) {
        result[i] = function(num) {
            return function() {
                console.log("this is " + num);
            }
        }(i);
    };

    return result;
}

It is working OK but why the anonymous function here not wrapped in parenthesis like this (function(...))(i); ? And in which cases can parenthesis be omitted in anonymous function?

like image 927
Johnny Chen Avatar asked Jul 08 '15 07:07

Johnny Chen


People also ask

Why are parenthesis used to wrap a JavaScript function call?

In JavaScript, the functions wrapped with parenthesis are called “Immediately Invoked Function Expressions" or "Self Executing Functions. The purpose of wrapping is to namespace and control the visibility of member functions. It wraps code inside a function scope and decrease clashing with other libraries.

How do you call an anonymous function?

Normally we use the function keyword before the function name to define a function in JavaScript, however, in anonymous functions in JavaScript, we use only the function keyword without the function name.

What is unique about an anonymous function?

An anonymous function is a function that is not stored in a program file, but is associated with a variable whose data type is function_handle . Anonymous functions can accept multiple inputs and return one output. They can contain only a single executable statement.

What is the difference between an anonymous and named function?

TL;DR Named functions are useful for a good debugging experience, while anonymous functions provides context scoping for easier development. Arrow functions should only be used when functions act as data.


1 Answers

Since the syntax for function declarations and function expressions is identical, JS tells which one you are using from the code around the function.

To stop it being a function declaration you need to use it in an expression. Wrapping it in parenthesis will will do that but preceding it with a = will too (as will a host of other operators). Since there is a = here, the parenthesis are unnecessary.

like image 102
Quentin Avatar answered Oct 20 '22 03:10

Quentin