Javascript - Using Arrow Functions to Create immediately invoked function expressions

Introduction

Functions in JavaScript can be used to create immediately invoked function expressions or IIFEs.

You could define an anonymous function and call it without having any reference to it.

var fn = function(number) { 
    return { 
        getNumber: function() { 
            return number; 
        } 
    }; 
}(42); 

console.log(fn.getNumber());      // 42 

Here, an IIFE is used to create the getNumber() method, which uses the number argument as a return value.

In this way, we ensure that the number property is effectively a private member of the returned object.

You can achieve the same logic using an arrow function.

Demo

var fn = ((number) => { 
    return { //  w ww  . java  2  s.  c o m
        getNumber: function() { 
            return number; 
        } 
    }; 
})(42); 

console.log(fn.getNumber());      // 42

Result

Arrow functions are function expressions and are not function declarations.

They are anonymous function expressions that have no named reference for the purposes of recursion or event binding or unbinding.

Related Topic