Arrow Function in JavaScript: How it Works with Examples

javascript arrow function

Arrow function gives you short code and keeps this in the right scope in JavaScript.

Understand the Arrow Function in JavaScript

An arrow function is a short way to write a function. It uses => to define behavior without the function keyword.

The syntax looks like this:

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

This code takes two numbers and returns the sum.

Arrow functions give you a structure for callbacks or quick one-line logic.
They also keep the scope of this keyword fixed inside objects and classes.

Here is a quick example:

const double = x => x * 2;
console.log(double(5));

This example doubles the number. The function uses one parameter and a direct return.

Arrow functions fit well in array methods, callbacks, and simple return logic.
Use regular functions if you need to use this keywords.

The Difference Between Arrow Functions and Regular Functions

Arrow functions use => and skip their own this. Regular functions use function and define their own this.

Here is a table that shows you the key differences for each one:

AspectArrow FunctionRegular Function
SyntaxShort with =>Uses function keyword
this bindingTakes scope from outsideDefines its own scope
Return statementDirect in one lineneeds a return

You can use the arrow functions for array tasks or callbacks, while the regular functions if you need to use this keyword.

Arrow Functions with Parameters and Return Values

Arrow functions can take no parameter, one parameter, or many. They can also return direct values or blocks with more logic.

Here is an example:

const greet = () => "Hello FlatCoding Students!";
console.log(greet());

This example has no parameter and returns a simple string.

Here is another example:

const multiply = (x, y) => {
  let result = x * y;
  return result;
};
console.log(multiply(4, 3));

This example takes two numbers, multiplies them, and returns the product.

Arrow Functions and this Binding Explained

Arrow functions do not bind their own this. They take it from the scope in which they exist.

For example:

function Person() {
  this.age = 0;
  setInterval(() => {
    this.age++;
  }, 1000);
}

This example shows how this within the arrow function still points to the object.

For another example:

const obj = {
  name: "Sam",
  show: function() {
    setTimeout(() => {
      console.log(this.name);
    }, 500);
  }
};
obj.show();

This example shows that this inside an arrow function points to obj object.

Arrow Function in JavaScript Callbacks and Array Methods

Arrow functions shorten code in callbacks. They also make array methods more direct and readable.

Here is an example:

const nums = [1, 2, 3, 4];
const squares = nums.map(n => n * n);
console.log(squares);

This example maps an array of numbers into a new array of squares.

For another example:

const nums = [5, 12, 18, 7];
const big = nums.filter(n => n > 10);
console.log(big);

This example filters out numbers greater than ten and creates a new array.

Examples of Arrow Function in JavaScript

Arrow Function for Array Reduce:

const nums = [2, 4, 6, 8];
const sum = nums.reduce((a, b) => a + b, 0);
console.log(sum);

It uses an arrow function with the reduce and starts from zero. It adds each number to create a single sum with short syntax.

Arrow Function with Default Parameter:

const power = (base, exp = 2) => base ** exp;
console.log(power(5));
console.log(power(5, 3));

This example shows default parameters. The function squares the number if no second value exists.

Arrow Function Inside an Object:

const obj = {
  nums: [1, 2, 3],
  print: function() {
    this.nums.forEach(n => console.log(n));
  }
};
obj.print();

This example shows arrow functions inside an object method. The this keyword points to the object and prints each number in the array.

Arrow Function with Promise:

const fetchData = () => new Promise(resolve => resolve("Data loaded"));
fetchData().then(data => console.log(data));

This example shows arrow functions inside a promise. The function creates a promise and resolves it with text. The .then method prints the text.

Wrapping Up

You learned what arrow functions are and how they are different from regular functions.

Here is a quick recap:

  • Arrow functions use short syntax with =>.
  • They keep this from outside the scope.
  • You can use it inside callbacks and array methods.
  • You have to use the regular functions for constructors or to bind this keyword.

FAQs

What is Arrow Function in JavaScript?

Arrow Function in JavaScript is a shorter way to write functions. It uses the syntax: const add = (a, b) => a + b; Example:
const greet = () => "Hello World";
console.log(greet()); // Hello World

How to use Arrow Function with parameters?

Arrow Functions can take parameters like normal functions. Example with single parameter:
 x * x;
console.log(square(5)); // 25
Example with multiple parameters:
const sum = (a, b) => a + b;
console.log(sum(3, 4)); // 7

What is the difference between Arrow Function and regular function?

  • Arrow Function does not bind this.
  • Regular Function binds this to its caller.
Example:
function normal() {
  console.log(this);
}

const arrow = () => {
  console.log(this);
};

normal(); // refers to its caller
arrow();  // refers to outer scope

Can Arrow Functions be used inside array methods?

Yes, Arrow Functions are common in array methods. Example:
const numbers = [1, 2, 3, 4];

const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8]

const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4]

Similar Reads

JavaScript Math acos Function

The Math.acos function finds the angle in radians from a cosine value in JavaScript. It gives a value between 0…

JavaScript for…in Loop: Iterating Over Objects

You may need to loop through properties when you work with objects in JavaScript. The for...in loop helps you do…

JavaScript switch Statement: Syntax and Examples

JavaScript switch statement checks many values without long chains. It appeared to replace stacked conditions that slow you down. Understand…

JavaScript Ninja Code for Beginners

JavaScript Ninja Code points to ways that help a person write code that runs fast and stays easy to read.…

JavaScript Math sqrt: How to Find Square Root of a Number

JavaScript Math.sqrt() solves the need to get square roots fast. Before it, you wrote custom code or used loops. It…

JavaScript toSorted Function Guide with Examples

This guide shows how toSorted function works in JavaScript with arrays. It covers syntax, rules, and examples for numbers, text,…

JavaScript toSpliced Function Explained with Examples

The toSpliced function creates a new array without changing the original array in JavaScript. It returns a copy with new…

JavaScript toReversed Function with Examples

JavaScript toReversed returns a new array with the reversed order of its elements. It does not change the original array…

How to Use the Ternary Operator in JavaScript

The ternary operator in JavaScript keeps your code short. It helps you write conditions inside one line. JavaScript lets you…

JavaScript for Loop: How to Iterate Arrays by Examples

JavaScript runs code in different ways, but the for loop stays one of the most common tools. You use it…

Previous Article

PHP array_all Function: How it Works with Examples

Next Article

PHP array_intersect_uassoc: How it Works with Examples

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.