Immediate function using JavaScript ES6 arrow functions

17,821

Solution 1

From the Arrow functions examples,

(() => "foobar")() // returns "foobar" 

So, the function invocation operator should be outside.

(() => {
  //...
})();

Sample: http://www.es6fiddle.net/hsb8s1sj/

Solution 2

Here is my demo codes!

Always remember that function_name+() === function_caller

/* ES5 */

// normal function

function abc(){
    console.log(`Hello, ES5's function!`);
}
abc();

var abc = function xyz(){
    console.log(`Hello, ES5's function!`);
};
abc();

// named function

var abc = function xyz(){
    console.log(`Hello, ES5's function!`);
}();


// anonymous function
// 1
(function(){
    console.log(`Hello, ES5's IIFE!`);
})();

// 2
(function(){
    console.log(`Hello, ES5's IIFE!`);
}());

// 3

var abc = function(){
    console.log(`Hello, ES5's function!`);
}();


/* ES6 */

// named arrow function
const xyz = () => {
    console.log(`Hello, ES6's Arrow Function!`);
};
xyz();


const xyz = (() => {
    console.log(`Hello, ES6's Arrow Function!`);
})();


// Uncaught SyntaxError: Unexpected token (

/*
const xyz = (() => {
    console.log(`Hello, ES6's Arrow Function!`);
}());
*/

// anonymous arrow function
(() => {
    console.log(`Hello, ES6's Arrow Function!`);
})();

Using ES6 Arrow Functions realize IIEF!

Immediately-invoked function expression

let x;

(x = () => {
  console.log(`ES6 ${typeof(x)}`);
})();

// ES6 function

// OR

(() => {
  console.log(`ES6 ${typeof(Symbol)}`);
})();

// ES6 function
Share:
17,821

Related videos on Youtube

d13
Author by

d13

Updated on February 08, 2022

Comments

  • d13
    d13 over 2 years

    Does anyone know how to write an immediate function using ES6 arrow syntax?

    Here's the ES3/5 way of doing it:

    (function () {
       //...
    }());
    

    I've tried the following but get an unexpected token error on the last line.

    (() => {
      //...
    }());
    

    You can test this here: http://www.es6fiddle.net/hsb8bgu4/

    • Jonathan Lonowski
      Jonathan Lonowski over 10 years
      Close the grouping before calling -- })(); es6fiddle.net/hsb8ot2m
    • Bergi
      Bergi almost 9 years
      This might be a traceur bug (probably related to this issue). It works fine with babel (repl demo)
    • xgqfrms
      xgqfrms about 7 years
      Always remember that function_name +` ()` === function_caller
  • callum
    callum about 9 years
    This way works with regular functions too, and it just makes more sense anyway - wrapping the function itself to make it an expression, then calling that expression. The fact that it also works when you wrap the whole function call is a weird quirk imo, I'm glad this doesn't work with arrows
  • xgqfrms
    xgqfrms over 7 years
    "Immediately-invoked function expression" as a term describes a design pattern which has also been referred to as a "self-executing anonymous function."