JavaScript Anonymous Function

JavaScript Anonymous Function with Examples

In this article, I am going to discuss JavaScript Anonymous function with Examples. Please read our previous article where we discussed JavaScript Asynchronous and synchronous Callback functions. In this article, we will discuss what it is? and how it works? we already have seen and understood this in the function article. Let gets reshape it with little more details.

Anonymous function in JavaScript:

When a function is defined, we often give it a name and then invoke it using that name which is called named function. like so:

Example: named function

Anonymous function in JavaScript

When we define a function this way, the JavaScript runtime stores our function in memory and then creates a reference to that function, using the name we’ve assigned it. That name is then accessible within the current scope. This can be a very simplest way to create a function, but JavaScript does not require us to assign a name to a function. The following is also legal way:

Anonymous function in JavaScript with Examples

When a function is defined without a name, it’s known as an anonymous function. The function is stored in memory, but the runtime doesn’t automatically create a reference to it for you. At first glance, it may appear as if such a thing would have no use, but there are several scenarios where anonymous functions are very convenient.

Example: Anonymous Function

How to create Anonymous Function in JavaScript

Anonymous Functions are different from Named Functions in JavaScript by not having a function name with which it refers to. The function without a name is called an “anonymous function” whereas the function with a name is called a “named function”

Below is the example that depicts the difference between them.
<html>
<head>
    <title>JavaScript named and anonymous function example</title>
</head>
<body>
    <script>        
        // Named function
        function nameShowMessage() {
            let x;
            x = 'JavaScript by Shagufta!'
            console.log(x);
            return x;            
        }

        // Anonymous function
        const anonyShowMessage = function () {
            let y;
            y = 'JavaScript by Shagufta!'
            console.log(y);
            return y;            
        }

        nameShowMessage();// Named function
        anonyShowMessage();// Anonymous function
    </script>
</body>
</html>

Output:

Anonymous function features

Anonymous Function Features:

anonymous functions are functions without a name. They are stored in a variable and are automatically called using the variable name. for e.g.:

var x = function (a, b) {
            console.log(a + b)
        }
x(3, 5)//15

An anonymous function can be used as a parameter to other functions or as an immediately invoked function (IIF) execution. Due to JavaScript’s asynchronous nature, anonymous functions are integral and are used much more often than in other languages. An anonymous function that is a nameless function that is created on the fly, and often used as the argument to another function to be run later as a callback function.

Named Function VS Anonymous Function in JavaScript

Named function and anonymous function behave differently when handling recursion.

Named Function VS Anonymous Function in JavaScript

The below example elaborates it in brief.

Example: calling anonymous function before its declaration example
<html>
<head>
    <title>JavaScript calling anonymous function before its declaration example</title>
</head>
<body>
    <script>
        anonyFunc();
        var anonyFunc = function () { // using an anonymous function
            console.log('anonymous Function');
        }

    </script>
</body>
</html>

Output:

calling anonymous function before its declaration example

Example: calling named function before or after its declaration example
<html>
<head>
    <title>JavaScript calling named function before or after its declaration example</title>
</head>
<body>
    <script>
        nameFunc();
        function nameFunc() { // using a named function
            console.log('named Function');
        }
    </script>
</body>
</html>

Output: named Function

Three Main Ways to Define Anonymous Functions. There are three Main Ways to declare Anonymous Functions:

IIFE (Immediately Invoked Function Expression)

(function (x) { return x * 2; })(2); About IIFE will learn more about this in the IIFE article.

Assignment to Variable

var multiplyByTwo = function (x) { return x * 2; };

Anonymous Functions used as a parameter passed to another function

[1, 2, 3, 4, 5].map(function (x) { return x * 2; });

Assigning an Anonymous Function to a variable

A very common use of anonymous functions is to assign them to a variable and are invoked automatically by using the variable name. In a simple way, once a function has been stored in a variable, the variable can be used as a function. The same has been illustrated as below

Example:
<html>
<head>
    <title>JavaScript assigning anonymous function to a variable example</title>
</head>
<body>
    <script>
        var f=function() {
            console.log('hello')
        }

        f();
    </script>
</body>
</html>

Output: hello

We will be going to discuss the use of anonymous functions in Functions as a variable in detail.

Function as Variable

A normal function declaration looks like this:

Assigning an Anonymous Function to a variable

A function defined like this is accessible from anywhere within its context by its name. But sometimes it can be useful to treat function references like object references. For example, we can assign an object to a variable based on some set of conditions and then later retrieve property from one or the other object:

Example: JavaScript assigning named function to a variable
<html>
<head>
    <title>JavaScript assigning regular/named function to a variable example</title>
</head>
<body>
    <script>
        var name = 'javascript';
        var spouse;
        if (name === 'java')
            spouse = {
                name: 'programming language'
            };
        else if (name === 'javascript')
            spouse = {
                name: 'scripting language'
            };
        var spouseName = spouse.name;
        console.log(spouseName);
    </script>
</body>
</html>

Output: scripting language

In the above example, the spouse is an object and name is the object property which we are assigning it to the variable spouseName. In JavaScript, we can do the same thing with anonymous functions.

Example: JavaScript assigning an anonymous function to a variable
<html>
<head>
    <title>JavaScript assigning anonymous function to a variable example</title>
</head>
<body>
    <script>
        var father = 'shah';
        var son;

        if (father === 'shah') son = function (value) {
            console.log('shah\'s son', value);
        };
        else if (father === 'watson') son = function (value) {
            console.log('watson\'s son', value);
        };

        son('junior shah');
    </script>
</body>
</html>

Output: shah’s son junior shah

In the above example, we have referenced the anonymous function. A function that does not have their own name. we can also use variables to refer to name this function.

Passing an anonymous function as an argument to another function

Some functions may accept a reference to a function as an argument. These are sometimes referred to as “dependency injections” or “callbacks”, because it allows the function of your calling to “call back” to your code, giving us an opportunity to change the way the called function behaves.

For example, the Array object’s map function allows us to iterate over each element of an array, then create a new array by applying a transform function to each element.

Example1: JavaScript passing an anonymous function as an argument to another function
<html>
<head>
    <title>JavaScript Passing anonymous function as an argument to another function example1</title>
</head>
<body>
    <script>
        var nums = [0, 1, 2];
        var doubledNums = nums.map(function (element) { return element * 2; }); // [0,2,4]

        console.log(doubledNums)
    </script>
</body>
</html>

Output:

Anonymous Function Examples in JavaScript

Example2:
<html>
<head>
    <title>JavaScript Passing anonymous function as an argument to another function example2</title>
</head>
<body>
    <script>
        setTimeout(function () {
            console.log('Execute later after 1 second')
        }, 1000);
    </script>
</body>
</html>

Output: Execute later after 1 second

In the above example, we pass an anonymous function into the setTimeout() function. The setTimeout() function executes this anonymous function one second later.

It would be tedious, and unnecessary to create a named function, which would mess up our scope with a function only needed in this one place and break the natural flow and reading of our code.

Returning an Anonymous Function from Another Function

Sometimes it’s useful to return a function as the result of another function.

Example:
<html>
<head>
    <title>JavaScript Returning an Anonymous Function from Another Function example</title>
</head>
<body>
    <script>
        var hash = getHashFunction('sha1');
        var hashValue = hash('Secret Value');

        function getHashFunction(algorithm) {

            if (algorithm === 'sha1')
                return function (value) {
                    return value;
                };
            else if (algorithm === 'md5')
                return function (value) {
                    return value;
                };
        }

        console.log("hash: ", hash)
        console.log("hashValue: ", hashValue)
    </script>
</body>
</html>

Output:

Advantages and Disadvantages of JavaScript Anonymous function

Advantages of Anonymous function:
  1. JavaScript allows us to pass an anonymous function as an object to other functions. We don’t need to explicitly define the function before passing it as a parameter to another function.
  2. It used as the parameter to another function to be run later as a callback function or as an immediately invoked function (IIF) execution.
Disadvantages of Anonymous function:
  1. The anonymous function cannot be reused.
  2. An anonymous function cannot be unit tested easily. In order to perform a unit test, we may need to refactor the code.
  3. When we have a large program written then debugging this function is tough because we don’t know the name of the function in the call stack. The call stack will show it as an anonymous function.

In the next article, I am going to discuss JavaScript Immediately Invoked Function Expressions (IIFE) with Examples. Here, in this article, I try to explain JavaScript Anonymous function with examples. I hope this JavaScript Anonymous function article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this JavaScript Anonymous function article.

Leave a Reply

Your email address will not be published.