xxxxxxxxxx
// The usual way of writing function
const magic = function() {
return new Date();
};
// Arrow function syntax is used to rewrite the function
const magic = () => {
return new Date();
};
//or
const magic = () => new Date();
xxxxxxxxxx
let func = (a) => {} // parentheses optional with one parameter
let func = (a, b, c) => {} // parentheses required with multiple parameters
xxxxxxxxxx
'use strict';
var obj = { // does not create a new scope
i: 10,
b: () => console.log(this.i, this),
c: function() {
console.log(this.i, this);
}
}
obj.b(); // prints undefined, Window {...} (or the global object)
obj.c()
xxxxxxxxxx
textBox.addEventListener('keydown', (event) => {
console.log(`You pressed "${event.key}".`);
});
xxxxxxxxxx
const introduction = () => {
console.log("Hello, my name is Jessica.");
};
xxxxxxxxxx
/*The arrow functions were introduced in ECMA 2015 with the main purpose of giving a shorter syntax to a function expression.
Besides providing shorter syntax, which increases the readability of the code,
it does not have its own value of the this object. The value of this object inside an arrow function is inherited from the enclosing scope.
You can write an arrow function to add two numbers as shown in the next code example.*/
var add = (num1, num2)=> num1+num2;
let res = add(5,2);
console.log(res); // 7
xxxxxxxxxx
let nums = [3, 5, 7]
let squares = nums.map(function (n) {
return n * n
})
console.log(squares)