Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare a function without a name in JavaScript

I am new to JavaScript (coming from Java) and want to understand this function

(function (global, factory) {
if (typeof define === 'function' && define.amd) {
    define(['../numeral'], factory);
} else if (typeof module === 'object' && module.exports) {
    factory(require('../numeral'));
} else {
    factory(global.numeral);
}

}

It's from this github page https://github.com/adamwdraper/Numeral-js/blob/master/src/formats/currency.js

My question is: Why isn't there a name for the function that takes global and factory as parameter ?

What I would expect is something like this:

function myFunction(p1, p2) {
return p1 * p2;   // The function returns the product of p1 and p2
}

Here, we have the name myFunction but in the above example, we don't have a name for the function. Why? And why is that allowed in JavaScript?

like image 269
Blnpwr Avatar asked Aug 30 '25 17:08

Blnpwr


2 Answers

Yes. They are called anonymous functions in Javascript.

Usually these functions are supplied as callbacks to another function.

Or they could be immediately invoked as Jack said in his answer.

like image 200
tys Avatar answered Sep 02 '25 07:09

tys


It's because it's in an IIFE - you don't need to name the function, and the only real use of naming it would be recursion.

It's like this:

var func = function (global, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['../numeral'], factory);
    } else if (typeof module === 'object' && module.exports) {
        factory(require('../numeral'));
    } else {
        factory(global.numeral);
    }
}

You call it like:

(func)();

Or:

func();

It's a function expression - it doesn't have a name, it's assigned to a named variable. Unnamed functions are known as anonymous functions, and you use them as testing/callback functions.

like image 34
Jack Bashford Avatar answered Sep 02 '25 05:09

Jack Bashford