- Forums
- Javascipt
- Arrow Functions - How To Use JavaScript ES6 Arrow Functions
These are my notes on how to use Javascript ES6 Arrow Functions [4977], Last Updated: Mon Jun 24, 2024
edwin
Sat Mar 19, 2022
0 Comments
533 Visits
JavaScript Arrow Functions
Basic - No parameter then requires Parentheses
const hello = () => "hello";
//USAGE:
console.log(hello());//Result: "hello"
Basic with parameter - No Parentheses required
hello = name => "Hello " + name;
//USAGE:
console.log(hello('John')); //Result: "Hello John"
Parentheses required if:
- 2 or more parameters
- Rest parameters
- Destructuring
- Objects
Examples
1. 2 or more parameters
hello = (fname,lname) => "hello" + fname + " " + lname;
2. Rest parameters
const numbers = (first, ...rest) => rest;
console.log(nums(1, 2, 3, 4)); //Result: [ 2, 3, 4 ]
3. Destructuring
const stateCapital = {
state: "California",
capital: "Sacramento"
};
const travel = ({capital}) => capital;
console.log(travel(stateCapital)); //Result: "Sacramento"
4. Objects
const f = () => ({
city:"Sacramento"
})
console.log(f().city)//Result: "Sacramento"
Object: ERROR if no Parentheses
const f = () => {
city: "Sacramento"
}