Skip to main content

Command Palette

Search for a command to run...

Hitting the Bull's Eye with Arrow Functions

get to know how they make your life easier

Updated
3 min read
Hitting the Bull's Eye with Arrow Functions

Does Arrow function has 🏹?

yeah kind of . Well apart from fancy name it completely works like a regular function . It supports passing arguments and do whatever you want inside its block and return anything if you like.

const double= (a) => {  // => is the arrow u might be looking for
    return a*2
}

console.log(double(7)) //output 14

Did you feel weird ? Did you feel that this syntax is alien ? If you have worked with regular functions then no .

const double = function( a ){
    return a*2
}

console.log(double(6) ) // output- 12

Difference in syntax from regular function.

in the example above what are the differences did you noticed ?

the only you can is "function" is replaced by => .

this helps to compress the code in fewer lines , i can literally write sum of 2 numbers in a single line .

const sum = (a,b) => a+b

console.log(sum(862,485)// 1347

Implicit return

in the example above did you notice i didn't use return keyword . The syntax of arrow function allows you to skip the {} and return , directly allowing you to type the return value .

Explicit return

const greet= (name)=>{
   return `Hello ${name}!`
}

console.log(greet("Reader")) // Hello Reader!

when you use both {} and return , then you are using explicit return as you mention that keyword explicitly .

Have you seen arrow function somewhere?

arrow functions are used to pass functions in higher order function( functions that accept as argument or return function as value ) .

eg in array.map()/ .reduce()/ .filter() etc.

let arr=[2,5,4,9,3,6,7]
let evenArr= arr.filter((element)=>element%2===0) // now that is a arrow function passed inside filter. 

console.log(evenArr) // [2,4,6]

they are called call back functions , just fancy names for same thing .

Lets write some arrow functions

1. check whether number is odd or even

const evenOdd = (a) =>{
     if( a%2===0) {
        console.log(`${a} is even')
        }
     else{ 
        console.log(`${a} is odd`)
        }
}
// directly console.log the value , so the function is not returning value

2. calculate n power m

const power = (n,m) => n**m

console.log(power(4,5)) 

3. usd to inr ( rates as on day of writing this blog)

const convert = ( usd ) =>{
    return `$${usd} is Rs.${usd*91.93}`
}

console.log(convert( 45 )) //$45 is Rs.4136.85

4. say hello to you friend

const hello = (friend )=>{
    console.log(`hello my friend ${friend}`)
}

you can write as many arrow functions as you can think of . I hope this introduces well enough with these pointy functions😎