//Long version
function add(a, b) {
return a + b;
}
// Shorthand
const add = (a, b) => a + b;
// Traditional Anonymous Function
function (a, b){
return a + b + 100;
}
// Arrow Function
(a, b) => a + b + 100;
// Traditional Anonymous Function (no arguments)
let a = 4;
let b = 2;
function (){
return a + b + 100;
}
// Arrow Function (no arguments)
let a = 4;
let b = 2;
() => a + b + 100;
const doSomething = () => {
// Function Scope
};
/*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
const = newfunc =(a,b)=>{
return a+b
}
let nums = [3, 5, 7]
let squares = nums.map(function (n) {
return n * n
})
console.log(squares)
const hello = () => {
return 'Hello'
}
const hello = () => 'Hello'
console.log(hello())
(param1, paramN) => {
let a = 1;
return a + param1 + paramN;
}
const bk = () =>{
console.log("Bk function called");
}
bk()
// Traditional Anonymous Function
function (a, b){
let chuck = 42;
return a + b + chuck;
}
// Arrow Function
(a, b) => {
let chuck = 42;
return a + b + chuck;
}
textBox.addEventListener('keydown', (event) => {
console.log(`You pressed "${event.key}".`);
});
let nums = [3, 5, 7]
let squares = nums.map((n) => {
return n * n
})
console.log(squares)
// Traditional Function
function (a){
return a + 100;
}
// Arrow Function Break Down
// 1. Remove the word "function" and place arrow between the argument and opening body bracket
(a) => {
return a + 100;
}
// 2. Remove the body brackets and word "return" -- the return is implied.
(a) => a + 100;
// 3. Remove the argument parentheses
a => a + 100;
// Arrow function with two arguments const sum = (firstParam, secondParam) => { return firstParam + secondParam; }; console.log(sum(2,5)); // Prints: 7 // Arrow function with no arguments const printHello = () => { console.log('hello'); }; printHello(); // Prints: hello // Arrow functions with a single argument const checkWeight = weight => { console.log(`Baggage weight : ${weight} kilograms.`); }; checkWeight(25); // Prints: Baggage weight : 25 kilograms. // Concise arrow functionsconst multiply = (a, b) => a * b; console.log(multiply(2, 30)); // Prints: 60