1 JQbkd18tw 9smovA9T3Rug

Arrow function syntax – what is arrow function and how we use it?

Arrow function is a very interesting concept in JavaScript. It makes our functions precise, meaningful and easy to read. Let’s code this. This is a function which is showing a string inside it. 

function myFunction(){
    console.log('I am a function')
}
myFunction()

We can convert this function into arrow notation very easily. 

const myFunction = () => {
    console.log('I am a function')
}
myFunction()

Here we are declaring a variable and assigning a function to it. Then we are calling this function, simple. We can even write this and it will work. 

const myFunction = () => console.log('I am a function') 
myFunction()

Now let’s pass one variable to the function. 

function addFive(num){
    return num+5
}
console.log(addFive(1))

We can convert this function into arrow notation in 3 ways. 

const addFive = (num) => {return num+5}
const addFive = (num) => ( num+5)
const addFive = num => num+5

All three notations are fine but I recommend using the last one. Now let’s pass 2 variables in the function. 

function add(num1, num2){
    return num1+num2
}

Now we can reduce this function to arrow notation in 3 ways. 

const add = (num1, num2) => {
    return num1+num2
}
const add = (num1, num2) => (num1+num2)
const add = (num1, num2) => num1+num2

We can add 3, 4 or as many variables as we want in this. If there is one line in the function then we can skip any kinds of braces.

const add = (num1, num2) => num1+num2

If there is one expression in the function then we only need one set of braces. 

const add = (num1, num2) => (`num 1: ${num1} and num2: ${num2}`)

Now we can also return an Object in our arrow function. 

let name = 'Harper'
let age = 29
let weight = 65
const intro = (name, age, weight) => ({name, age, weight})
console.log(intro(name, age, weight))

I hope we have covered every possibility of the arrow function. Please remember that arrow notation is not valid when we use call(), apply() and bind() methods. 

If you have any questions please write that down in the comments section. We really appreciate that.