Skip to main content

Command Palette

Search for a command to run...

Arrow Functions in JavaScript: A Simpler Way to Write Functions

Updated
2 min read

If you have started learning JavaScript, you have probably written functions already. Functions help us group code together so we can reuse it whenever we need. But as programs grow, writing functions again and again using the traditional syntax can feel a bit repetitive. This is where arrow functions come in. They provide a shorter and cleaner way to write functions in modern JavaScript.

Let’s start with a simple example. Suppose we want a function that returns the square of a number. Using the traditional syntax, it would look like this:

function square(num) {
  return num * num;
}

Now let’s rewrite the same function using an arrow function:

const square = (num) => {
  return num * num;
};

Already, the code looks a little simpler. JavaScript allows us to simplify it even further. If a function has only one parameter, we can remove the parentheses.

const square = num => num * num;

In this version, JavaScript automatically returns the result. This is known as implicit return because we do not explicitly write the return keyword.

Arrow functions can also handle multiple parameters. In that case, parentheses are required.

const add = (a, b) => a + b;

Arrow functions are especially useful when working with arrays. For example, we can use them inside the map() method to transform values in an array.

const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2);

Here, each number in the array is multiplied by two, creating a new array with the updated values.

Overall, arrow functions make JavaScript code shorter, easier to read, and closer to modern coding practices. As you continue your journey in JavaScript, you will notice that arrow functions are used very frequently in real-world applications.