(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.
(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.
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.
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!
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.
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"