Arrow functions in Javascript

Arrow functions in Javascript

Functions in Javascript

Functions are at the heart of Javascript

Code is difficult to maintain, especially when you keep adding new features to your project over several months and years. It may happen that many parts of the project are apparently doing the same task or computation. Such similar tasks can be performed through functions. Functions help us structure larger programs.

Below are the ways in which we can write functions in Javascript.

Traditional method

In the traditional method, functions are defined using the function keyword. For example:

function getProduct(x, y){
   return (x * y);
}

Given that in JavaScript functions are first-class objects, the example above can be rewritten with an unnamed function assigned to a variable (a constant to be precise) called product:

const product = function(x, y){
   return (x * y);
}
console.log(product(2, 5)) // 10

This code is functionally similar to the first code.

Arrow functions

  • Arrow functions were one of the most noticeable features to JavaScript that were added with ES6 specification

  • Also known as "fat arrow functions". They are a shorter way to define functions.

  • The above traditional function can be converted into an arrow function by the following steps:

  1. Remove the word "function" and place an arrow between the argument and opening body bracket (x, y) => { return (x * y); }

  2. Remove the word "return" -- the return is implied. (x, y) => (x * y);

  3. Remove the parenthesis around the return statement. (x, y) => x * y;

Finally, the arrow function will look like this:

const getProduct = (x, y) => x * y;
console.log(getProduct(2, 5)) // 10

Every function in Javascript is a function object

Things to keep in mind regarding arrow functions:

  • No parameters

    If there are no parameters passed on the arrow function, we just need to write the opening and closing round brackets.

    const greet = () => console.log("Hello, world!");
    
  • Single parameters

    When a single parameter is passed on to an arrow function, the parameter need not have round brackets around it.

const getSquare = x => x * x;
console.log(getSquare(5)) // 25
  • Multiple parameters

    When multiple parameters are passed on to an arrow function, the parameters can be enclosed inside the round brackets, similar to the traditional functions. The example that we discussed above has 2 parameters which are enclosed inside round brackets.

  • Still shorter...

    If the function body is only a single line, we can omit the parenthesis around the function body.

const myName = (name) => `my name is ${name}`; 
console.log(myName("Omkar"));
  • Returning object

    If you are returning an object then you need to wrap it in parentheses. This forces the interpreter to evaluate what is inside the parentheses, and the object literal is returned.
const createMilkshake = (name) => ({name, price: 150});

console.log(createMilkshake("chocolate")); // { name: 'chocolate', price: 150 }
  • Hoisting in arrow functions

    Like traditional function expressions, arrow functions are not hoisted, and so you cannot call them before you declare them.
//Below code works fine
    myName("omkar");
    const myName = (name) => console.log(`my name is ${name}`); 

// But below code give error: Uncaught TypeError sayHello is not a function
    myName("omkar");    
     var myName = () => {
        console.log("`my name is ${name}`");
    }
  • No arguments object

    Unlike the traditional functions, the arrow functions do not have the arguments object. However, the arrow function has access to the arguments object of a non-arrow parent function.
function getSum() {
    console.log(arguments[0] + arguments[1]);
}
getSum(1, 2); // 3

//But this gives  ReferenceError: arguments is not defined
const getSum = () => {
    console.log(arguments[0] + arguments[1]);
};
getSum(1, 2); // 3

Features

When to use arrow functions

  • If we need to write functions that iterate over a list of some items such as an array or string, then Arrow functions can be very useful. Common JavaScript methods such as map(), filter(), and reduce() can look much cleaner with the help of arrow functions. Example: Let's say you have an array of numbers, and you want to double the value of every element in the array. The traditional way to do this is
let numbers = [1, 2, 3, 4];

numbers.map(function(num) {
  return num * 2;
});

//output array: [2, 4, 6, 8]

Now, with the arrow function.

let numbers = [1, 2, 3, 4];

numbers.map(num => num * 2);  //output array: [2, 4, 6, 8]

Conclusion

Arrow functions are a necessity in JavaScript programming. They provide a revolutionary way to reduce code repetition and improve readability.

Just like learning any new concept, it is important to understand when it is best and when it is not best to use this type of function. I hope this blog has given a few helpful insights. Please leave a like or share if it is helpful in any way. Thanks for reading.

References