JavaScript: Arrow Functions

Profile picture for user arilio666

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()
{
    //body
}

1. Single-Line Arrow Function

Syntax

name = (parameter) => expression

Example

divideNum = (num, num2) => num / num2;
console.log(divideNum(233,22))

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;
console.log(mess('Shazam'))

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

Syntax

name = () => 
{
    //body
}

Example

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.