Skip to main content

Command Palette

Search for a command to run...

Cutting the Boilerplate with Arrow Functions

Why you should drop the function keyword and embrace the arrow.

Published
5 min read
Cutting the Boilerplate with Arrow Functions

You have encountered this piece of code multiple times at different places, in tutorials, GitHub:

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

This looks weird and alien at first, but once you understand this, it becomes a default for you to use in code.

What Are Arrow Functions?

Arrow functions are just a shorter way to write functions. That is the whole story. They behave similarly to regular functions in most cases; their syntax requires less typing and looks natural.

This is how a Function looks:

function greet(name) {
  return "Hello, " + name;
}

console.log(greet("User")); // "Hello, User"

The same function can be written using arrow functions:

const greet = (name) => {
  return "Hello, " + name;
};

console.log(greet("User")); // "Hello, User"

They produce the same output; the difference lies in the structure of the functions. The function keyword is dropped, and an arrow => is added between the parameter and the body.

Basic Syntax Breakdown


Arrow Function with Single Parameter

When arrow functions take a single parameter, the parentheses can be dropped.

// With parentheses, always valid
const shout = (word) => {
  return word.toUpperCase();
};

// Without parentheses, also valid with a single parameter
const shout = word => {
  return word.toUpperCase();
};

console.log(shout("hello")); // "HELLO"
💡
It is a good practice to use parentheses in your code to avoid confusion.

Arrow Function with Multiple Parameters

When you have two or more parameters, the parentheses are not optional. They are required.

// Two parameters
const add = (a, b) => {
  return a + b;
};

console.log(add(3, 5));  // 8

// Three parameters
const fullName = (first, middle, last) => {
  return first + " " + middle + " " + last;
};

console.log(fullName("Amar", "Akbar", "Anthony")); // "Amar Akbar Anthony"

When there are no parameters, parentheses are still needed:

const greetWorld = () => {
  return "Hello, World!";
};

console.log(greetWorld()); // "Hello, World!"

Implicit Return vs Explicit Return

An explicit return means you write the return keyword yourself, inside curly braces.

const square = (n) => {
  return n * n; // explicit return
};

An implicit return means the curly braces and the return keywords are dropped, and the arrow function will automatically return whatever expression follows the arrow:

const square = (n) => n * n; // implicit return

console.log(square(4)); // 16
console.log(square(9)); // 81

Here are some examples of the usage of these return types:

// Implicit

// Multiply two numbers
const multiply = (a, b) => a * b;
console.log(multiply(6, 7));  // 42

// Check if a number is even
const isEven = (n) => n % 2 === 0;
console.log(isEven(4));  // true
console.log(isEven(7));  // false

// Build a greeting string
const greet = (name) => `Hey, ${name}`;
console.log(greet("User"));  // "Hey, User"
// explicit

// Multi line body needs curly braces and explicit return
const describe = (n) => {
  const type = n % 2 === 0 ? "even" : "odd";
  return `\({n} is \){type}`;
};

console.log(describe(7));   // "7 is odd"
console.log(describe(12));  // "12 is even"

If curly braces are used, but the return keyword is not used, then the function would return undefined

const broken = (n) => { n * 2 }; // no return
console.log(broken(5)); // undefined

Arrow Functions vs Normal Functions

Feature Normal function Arrow function
Syntax function keyword required uses =>, no function keyword
Can be named yes only through the variable it is stored in
Hoisting declarations are hoisted to the top of the scope not hoisted (must be defined before use)
this keyword has its own this inherits this from the surrounding scope
arguments object Has its own arguments No arguments (Use ...args instead)
Use as constructor Yes, with new No, throws an error
Best used for methods, constructors, complex logic callbacks, array methods, short utilities

Hoisting of Arrow Function

Normal function declarations get hoisted to the top of their scope, which means you can call them before you define them in the file and it still works. Arrow functions stored in variables do not behave that way:

 // Normal function: this works 
console.log(sayHi()); // "Hi" -- called before definition

function sayHi() {
  return "Hi";
}

// Arrow function: this throws a ReferenceError
console.log(greet()); // ReferenceError: Cannot access before initialization

const greet = () => "Hi";

Arrow Function Importance

The arrow functions finds its real importance in array methods. Array Methods take a function as an argument, and make the code readable when used with arrow functions.

For example, there is an array of product prices and 10% discount is applied to it:

const prices = [29.99, 49.99, 9.99, 89.99];

// Using a normal function inside map
const discounted = prices.map(function(price) {
  return price * 0.9;
});

// Using arrow function
const discounted = prices.map((price) => price * 0.9);

console.log(discounted);
// [26.991, 44.991, 8.991, 80.991]

The arrow function makes things fit in a single line.


REFERENCES:

Simply JavaScript

Part 16 of 25

JavaScript is a quirky language. To master it, one should know to avoid its hidden traps along with its logic. This series showcase my journey through JS: the pain points, the breakthroughs, and the coding standards that I adopted from my mentors.

Up next

JS Functions Demystified: Declarations vs. Expressions

Stop guessing which one to use. Learn exactly how JavaScript handles function syntax, hoisting behaviors, and variable assignments.