Wednesday, November 24, 2021

What is Arrow function in javascript?

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[3121111]

//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 write return.

const add = (a,b) => {
return a + b;
}

If you forget:

const add = (a,b) => {
a + b;
}
console.log(add(2,3)); // undefined
this behavior:
Arrow functions do NOT create their own this.
const person = {
name: "Lokman",
  greet: function(){
console.log(this.name);
}
}

this → points to person

const person = {
name: "Lokman",

greet: () => {
console.log(this.name);
}
}

Output:undefined

Arrow function takes this from 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

Javascript module

JavaScript Modules (ES6) let you split code into multiple files and reuse code cleanly. Main keywords: export → make something available...