Loop and function in ESC 6part 2
Functions in ECMAScript 6
Prior to ES6, a JavaScript function was defined like this:
ES6 introduces a new syntax for writing functions. The same function from above can be written as:
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:
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
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:
However, in ES6, the code above can be rewritten as following:
The code is shorter and looks pretty nice, doesn't it? :)
Comments
Post a Comment