Home » Node.js

Anonymous function in Node JS

In this article, we are going to learn about the anonymous function in Node JS? What is it and how to use it in the code?
Submitted by Mansha Lamba, on October 20, 2018

Functions are the very basic and fundamental topic of any programming language. Understanding them in great detail is very much necessary for any programmer or coder.

Thus, in this article, I will throw light on anonymous functions in JavaScript.

They are a very strong tool for generating concise codes and are very commonly seen in JavaScript libraries.

Example:

(function(food) {
    if (food === "cookies") {
        console.log("More please");
    } else if (food === "cake") {
        console.log("Yum yum");
    }
})("cookies");

Output

anonymous function output | Node JS

Explanation:

It might seem to be very confusing on first glance, but it is not so.

In line number 7 we are just calling a function and passing cookies as an argument to it. But the function we are calling is anonymous i.e. it does not have a name.

So instead of using a function reference we are defining the function or using a function expression.

Also, pay attention that extra set of parenthesis is very much necessary for these kinds of function calling otherwise java interpreter won't be able to identify it as a function.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.