First example (old way):
const add = (x, y) => {
const sum = x + y;
return sum;
}
and it could be optimized to (2 arguments)
const add = (x, y) => x + y;
1 argument:
const double = number => number * 2;
0 arguments:
const sayHello = () => console.log('Hello');
if it has a return:
const getPersonaData = () => ({
name: 'Jhon Doe',
age: 34,
job: "programmer",
})
/*Without parenthesis it seems we
want to define the body of the function
*/
If it has a body and more than 1 statement brackets should be used {}
const myArrowFunction = (arg1,arg2)=>{
console.log("yeeee, charliee");
return arg1+arg2;
}
myArrowFunction(1,2);
yeeee, charliee
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.29/browser.js"></script>
<script type="text/babel">
var person = {
first: "Doug",
actions: ['bike', 'hike', 'ski', 'surf'],
printActions() {
this.actions.forEach(action => {
var str = this.first + " likes to " + action;
console.log(str);
});
}
};
person.printActions();
</script>
<title>Arrow Functions and 'this'</title>
</head>
<body>
</body>
</html>
Output:
Doug likes to bike
Doug likes to hike
Doug likes to ski
Doug likes to surf
Sources:
https://www.linkedin.com/learning/learning-functional-programming-with-javascript-es6-plus