Loop and function in ESC 6part 2

Functions in ECMAScript 6



Prior to ES6, a JavaScript function was defined like this:
function add(x, y) {
var sum = x+y;
console.log(sum);
}
Try It Yourself

ES6 introduces a new syntax for writing functions. The same function from above can be written as:
const add = (x, y) => {
let sum = x + y;
console.log(sum);
}
Try It Yourself

This new syntax is quite handy when you just need a simple function with one argument.
You can skip typing function and return, as well as some parentheses and braces.
For example:
const greet = x => "Welcome " + x;Try It Yourself

The code above defines a function named greet that has one argument and returns a message.

If there are no parameters, an empty pair of parentheses should be used, as in
const x = () => alert("Hi");Try It Yourself

The syntax is very useful for inline functions. For example, let's say we have an array, and for each element of the array we need to execute a function. We use the forEach method of the array to call a function for each element:
var arr = [2, 3, 7, 8];

arr.forEach(function(el) {
console.log(el * 2);
});
Try It Yourself

However, in ES6, the code above can be rewritten as following:
const arr = [2, 3, 7, 8];

arr.forEach(v => {
console.log(v * 2);
});
Try It Yourself

The code is shorter and looks pretty nice, doesn't it? :)

Comments