Arrow functions introduced in ES6. It provides a concise way to write JavaScript function.
//ES5
const years=[1990,2000,2010,2020];
var ages= years.map(function(el){
return 2021-el;
});
console.log(ages);
output: [31, 21, 11, 1]
//ES6
const years = [1990,2000,2010,2020];
let ages = years.map(el=>2021-el); //This is called arrow function.
console.log(ages);
output: [31, 21, 11, 1]
//Arrow function with multiple parameter
const years = [1990,2000,2010,2020];
let ages = years.map((el,index)=>`age element ${index+1}:${2021-el}`);
console.log(ages);
map decides which one is value and which one is index
Implicit return (no {})
JavaScript automatically returns the expression.
const add = (a,b) => a + b;
Same as:
const add = function(a,b){
return a + b;
}Explicit return (with{})If you use
{}, you must writereturn.const add = (a,b) => {
return a + b;
}If you forget:
Arrow function takesconst add = (a,b) => {
a + b;
}
console.log(add(2,3)); // undefinedthisbehavior:Arrow functions do NOT create their ownthis.const person = {
name: "Lokman",
greet: function(){
console.log(this.name);
}
}
this→ points topersonconst person = {
name: "Lokman",
greet: () => {
console.log(this.name);
}
}Output:undefined
thisfrom outer scope, not from the object.Example where arrow helps:
const person = {
name: "Lokman",
greet() {
setTimeout(() => {
console.log(this.name);
}, 1000);
}
};
person.greet();Output:Lokman
Returning objects
const createUser = () => { name: "Lokman" };
JavaScript thinks {} is a function body.
Result: undefined
Correct way:
const createUser = () => ({ name: "Lokman" });
Wrap object in ().
Arrow functions are NOT for methods or constructors
No comments:
Post a Comment