JavaScript: Arrow Functions

There is an arrow function where we can use functions in javascript with more minimalistic syntax and can yield much more easy-to-use code. We can call it a much shorter version of the normal javascript function.

Function before

name = function()

1. Single-Line Arrow Function


name = (parameter) => expression


divideNum = (num, num2) => num / num2;

Output: 10.590909090909092

Here as per the syntax we have started a function named divideNum and passed in the respective parameters to get that divided and yield result.

Now if we want we can also not use the () when we use a single parameter.

mess = message => message;

Output: Shazam

Like here we have given a parameter and so on ignored the (). If there are no parameters the () should be present no matter what this is a case just for a single parameter.

2. Multi-Line Arrow Functions


name = () => 


When we wanna use multi-line expressions we might wanna use the following syntax instead of the above one. Because the above one only works with a single-line statement.

mul = (x, y) => 
    let res = x * y;
    return res;

console.log(mul(3, 2))

Output: 6

So this is the example for multi-line arrow function usage. We must always use curly braces when we are gonna use this multi-line arrow function to add more expressions and conditions within them.

Mon, 11/01/2021 - 08:15

Authored by

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.