0
(a => `Hello ES${a}`)(2015);

The above code return Hello ES2015 but i'm unable to understand how the template literals work here with arrow function.

VinKrish
  • 357
  • 1
  • 5
  • 17
  • 1
    `(a => ``Hello ES${a}``)(2015);` `a` is the parameter which receives `2015` as argument . The function returns 'Hello ES`a`' – Daut Jan 15 '19 at 14:28
  • 4
    Possible duplicate of [What is the (function() { } )() construct in JavaScript?](https://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript) – str Jan 15 '19 at 14:29
  • 4
    So you recognised the arrow function and the template literal. What exactly is unclear, how the expression becomes the return value? – Bergi Jan 15 '19 at 14:31

4 Answers4

1

It's an IIFE (Immediately Invoked Function Expression).

It defines an anonymous function that takes a parameter a and returns a string concatenating Hello ES with the value of a.

a => `Hello ES${a}`

/* is equivalent to:

   function(a) {
     return 'Hello ES' + a
   }
*/

Then, it runs this function applying the value 2015 as parameter.

0xc14m1z
  • 3,675
  • 1
  • 14
  • 23
1

Ok, let's try to understand it step by step. We have:

(a => `Hello ES${a}`)(2015);

We know that any arrow function from ES6 can be replaced by a normal function. So, keeping the brackets in place (the ones that have to stay in place), the above code is equivalent with:

(function (a) {
    return `Hello ES${a}`;
})(2015);

Now, this is a simple Immediately-Invoked Function Expression. The function is executed right after it's created, not after it is parsed. The entire script block is parsed before any code in it is executed. Also, parsing code doesn't automatically mean that it's executed, if for example the IIFE is inside a function then it won't be executed until the function is called. So, in your case, we have an immediate function call with the 2015 parameter, returning Hello ES2015.

You can read more about IIFEs here or here.

Cheers!

Adrian Pop
  • 1,879
  • 5
  • 28
  • 40
0

This is call IIFE (Immediately Invoke Function Expression), this is useful to run the function when you need it.

Actually by using arrow functions (lambda function) (a =>Hello ES${a})(2015); a is a parameter and all lambda function by default (without curly braces) return the next statement.

It's like the same behavior with if statement when you not define a block with curly braces. E.g.

if ( value === 'isFuture?')
  return 'Everyday it is'

Check the YouDontKnow series, https://github.com/getify/You-Dont-Know-JS.

Yoarthur
  • 909
  • 9
  • 20
0

It's the same as function auto execute : function(a) { return 'hello ES'+a}(); But the argument here is 2015 And that return "hello ES2015"

Conan
  • 319
  • 2
  • 9