Table of contents
1.
Introduction
2.
Syntax
2.1.
Key Points
3.
All Functions are Methods
3.1.
How It Works
4.
Method Reuse
4.1.
Why is Method Reuse Important?
4.2.
Another Example: Reusing a Function for Different Operations
4.3.
What is this?
5.
How Does Function Calling Work?
5.1.
Key Points to Remember
5.2.
Practical Use Case: Calculating Discounts
6.
The JavaScript call() Method
6.1.
Why Use call()?
6.2.
Advanced Example
6.3.
How Does the `call()` Method Work?
6.4.
Example: Using `call()` to Set the `this` Context
6.5.
Passing Arguments with `call()`
6.6.
Practical Use Case: Reusing Functions with Different Contexts
6.7.
When to Avoid Using call()
7.
JavaScript Function Call Examples
7.1.
Example 1: Using call() to Borrow Methods
7.2.
Example 2: Setting this to a Primitive Value
7.3.
Example 3: Using call() with Arguments
8.
Supported Browsers
9.
Frequently Asked Questions
9.1.
What is the difference between call() and apply()?
9.2.
Can call() be used with arrow functions?
9.3.
Is the call() method exclusive to functions?
10.
Conclusion
Last Updated: Jan 19, 2025
Easy

JavaScript Function Call

Author Pallavi singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

JavaScript is a versatile and dynamic programming language that powers the majority of modern web applications. One of its powerful features is the call() method, which allows developers to invoke a function with a specific value and arguments. 

JavaScript Function Call

In this article, we will discuss the syntax of the call() method, how it works with functions, various examples, and browser support.

Syntax

The syntax of the call() method is quite simple:

functionName.call(thisArg, arg1, arg2, ...)


Explanation:

  • functionName: The function you want to call.
     
  • thisArg: The value to be assigned to this inside the function.
     
  • arg1, arg2, ...: Optional arguments to be passed to the function.

Key Points

  1. If thisArg is null or undefined, this defaults to the global object (in browsers, it’s window).
     
  2. call() can be used with any function, making it highly flexible.

Here’s a simple example:

function greet(greeting, name) {
    console.log(greeting + ", " + name + "!");
}
greet.call(null, "Hello", "John");
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

Hello, John!

All Functions are Methods

In JavaScript, functions are first-class objects. This means that functions can be treated like objects and used as methods. With the call() method, any function can be executed as though it belongs to another object.

Example:

const person = {
    fullName: function() {
        return this.firstName + " " + this.lastName;
    }
};
const individual = {
    firstName: "Jane",
    lastName: "Doe"
};
console.log(person.fullName.call(individual));
You can also try this code with Online Javascript Compiler
Run Code


Output:

Jane Doe

How It Works

  • The fullName function is defined in the person object.
     
  • Using call(), it is invoked with the individual object as its this value.
     

This feature allows you to reuse functions across different objects, reducing redundancy and improving code modularity.

Method Reuse

In JavaScript, one of the most powerful features of functions is their ability to be reused. Method reuse means writing a function once & using it multiple times in different parts of your code. This saves time, reduces errors, & makes your code cleaner & easier to maintain.

Suppose you are building a program that calculates the area of different shapes. Instead of writing the same formula multiple times, you can create a function & reuse it whenever needed.

Let’s see how you can do it:

// Function to calculate the area of a rectangle
function calculateArea(length, width) {
    return length  width;
}
// Reusing the function for different rectangles
let area1 = calculateArea(5, 10); // Area of a 5x10 rectangle
let area2 = calculateArea(7, 3);  // Area of a 7x3 rectangle
console.log("Area 1:", area1); 
console.log("Area 2:", area2); 
You can also try this code with Online Javascript Compiler
Run Code

 

Output: 

Area 1: 50
Area 2: 21


In this example, the `calculateArea` function is defined once but used twice to calculate the area of two different rectangles. This is method reuse in action. You don’t need to rewrite the formula every time; instead, you just call the function with different values.

Why is Method Reuse Important?

1. Saves Time: You write the code once & use it multiple times.
 

2. Reduces Errors: If you need to fix a bug or update the logic, you only need to change it in one place.
 

3. Improves Readability: Your code becomes easier to understand because repetitive tasks are handled by functions.

Another Example: Reusing a Function for Different Operations

Let’s say you want to create a function that greets users. You can reuse this function to greet different people.

// Function to greet a user
function greetUser(name) {
    return "Hello, " + name + "!";
}
// Reusing the function for different users
let greeting1 = greetUser("Alice");
let greeting2 = greetUser("Bob");
console.log(greeting1); 
console.log(greeting2); 
You can also try this code with Online Javascript Compiler
Run Code


Output: 

Hello, Alice!
Hello, Bob!


Here, the `greetUser` function is reused to greet two different users. This shows how method reuse makes your code efficient & scalable.

What is this?

When we talk about "calling a function" in JavaScript, we’re referring to the process of executing the code inside that function. Think of a function as a set of instructions stored in a box. When you "call" the function, you’re telling the program to open the box & follow those instructions.

Let’s take a simple example to understand this better:

// Defining a function
function sayHello() {
    console.log("Hello, World!");
}
// Calling the function
sayHello(); 
You can also try this code with Online Javascript Compiler
Run Code


Output: 

Hello, World!


In this example, the function `sayHello` is defined with a single instruction: to print "Hello, World!" to the console. When we write `sayHello()`, we’re calling the function, & the program executes the code inside it.

How Does Function Calling Work?

1. Function Definition: First, you define the function using the `function` keyword. This is where you write the code that will be executed when the function is called.
 

2. Function Call: To execute the function, you use its name followed by parentheses `()`. This tells JavaScript to run the code inside the function.

Let’s take a look at an another example to make it clearer:

// Function to add two numbers
function addNumbers(a, b) {
    return a + b;
}

// Calling the function with arguments
let result = addNumbers(3, 5);
console.log("The sum is:", result); 
You can also try this code with Online Javascript Compiler
Run Code


Output: 

The sum is: 8

In this case:

  • The function `addNumbers` is defined to take two arguments (`a` & `b`) & return their sum.
     
  • When we call `addNumbers(3, 5)`, the values `3` & `5` are passed as arguments to the function.
     
  • The function calculates the sum & returns the result, which is then printed to the console.

Key Points to Remember

1. Function Definition: The code inside a function doesn’t run until the function is called.
 

2. Function Call: You can call a function as many times as you need, & it will execute the same code each time.
 

3. Arguments: Functions can take inputs (called arguments) to perform operations based on those inputs.

Practical Use Case: Calculating Discounts

Let’s say you’re building an e-commerce website & need to calculate discounts for different products. You can create a function to calculate the discounted price & reuse it for multiple products.

// Function to calculate discounted price
function calculateDiscount(price, discountPercentage) {
    let discountAmount = (price  discountPercentage) / 100;
    return price - discountAmount;
}
// Calling the function for different products
let product1 = calculateDiscount(1000, 20); // 20% discount on a $1000 product
let product2 = calculateDiscount(500, 15);  // 15% discount on a $500 product
console.log("Product 1 price after discount:", product1); 
console.log("Product 2 price after discount:", product2); 
You can also try this code with Online Javascript Compiler
Run Code

 

Output: 

800
425


In this example, the `calculateDiscount` function is called twice with different arguments, demonstrating how function calling works in real-world scenarios.

The JavaScript call() Method

The call() method is a powerful utility for invoking functions in different contexts. Its ability to set this value makes it particularly useful in scenarios where functions need to operate on varying objects.

Why Use call()?

  1. Code Reusability: You can use one function with multiple objects without duplication.
     
  2. Dynamic Contexts: Functions can adapt dynamically based on the provided this value.

Advanced Example

Using call() to calculate the area of different shapes.

function calculateArea(length, width) {
    return this.shape + " Area: " + (length * width);
}
const rectangle = { shape: "Rectangle" };
const square = { shape: "Square" };
console.log(calculateArea.call(rectangle, 10, 5));
console.log(calculateArea.call(square, 7, 7));
You can also try this code with Online Javascript Compiler
Run Code


Output:

Rectangle Area: 50
Square Area: 49

How Does the `call()` Method Work?

The `call()` method takes two main components:

1. `thisArg`: The value to be used as `this` inside the function.
 

2. Arguments: A list of arguments to be passed to the function.


The syntax is:

functionName.call(thisArg, arg1, arg2, ...);


Let’s understand this with an example.

Example: Using `call()` to Set the `this` Context

Suppose you have an object representing a person & a function that greets the person using their name. You can use the `call()` method to set the `this` context to the person object.

// Object representing a person
let person = {
    name: "Alice",
    age: 25
};
// Function to greet the person
function greet() {
    console.log("Hello, " + this.name + "!");
}
// Using call() to set 'this' to the person object
greet.call(person); 
You can also try this code with Online Javascript Compiler
Run Code

 

Output: 

Hello, Alice!


In this example:

  • The `greet` function uses `this.name` to access the `name` property of the object.
     
  • By using `greet.call(person)`, we set `this` to refer to the `person` object, so `this.name` becomes `person.name`.

Passing Arguments with `call()`

The `call()` method also allows you to pass arguments to the function. Let’s modify the previous example to include a custom greeting message.

// Object representing a person
let person = {
    name: "Alice",
    age: 25
};
// Function to greet the person with a custom message
function greet(message) {
    console.log(message + ", " + this.name + "!");
}
// Using call() to set 'this' and pass an argument
greet.call(person, "Good morning"); 
You can also try this code with Online Javascript Compiler
Run Code

 

Output: 

Good morning, Alice!


In this code:

  • The `greet` function now takes a `message` argument.
     
  • When calling `greet.call(person, "Good morning")`, we pass `person` as the `this` context & `"Good morning"` as the `message` argument.

Practical Use Case: Reusing Functions with Different Contexts

Let’s say you have a function that calculates the total price of items in a shopping cart, & you want to reuse it for different customers.

// Function to calculate total price
function calculateTotal(discount) {
    let total = this.item1 + this.item2;
    return total - (total  discount) / 100;
}
// Object representing customer 1
let customer1 = {
    item1: 100,
    item2: 200
};
// Object representing customer 2
let customer2 = {
    item1: 150,
    item2: 300
};
// Using call() to calculate total for customer 1 with a 10% discount
let total1 = calculateTotal.call(customer1, 10);
console.log("Customer 1 total:", total1); 


// Using call() to calculate total for customer 2 with a 20% discount
let total2 = calculateTotal.call(customer2, 20);
console.log("Customer 2 total:", total2); 
You can also try this code with Online Javascript Compiler
Run Code

 

Output

270
360


In this example:

  • The `calculateTotal` function uses `this.item1` & `this.item2` to access the prices of items.
     
  • By using `call()`, we can reuse the same function for different customers & apply different discounts.


Key Takeaways:

1. `this` Context: The `call()` method allows you to explicitly set the `this` context for a function.
 

2. Arguments: You can pass arguments to the function directly using `call()`.
 

3. Reusability: This method is particularly useful when you want to reuse a function with different objects or contexts.

When to Avoid Using call()

While call() is versatile, avoid overusing it in scenarios where simpler alternatives (like regular method calls) suffice. Additionally, excessive reliance on call() can make code harder to read and maintain.

JavaScript Function Call Examples

Example 1: Using call() to Borrow Methods

Suppose you have an object with a method, and you want another object to use it.

const mathOperations = {
    add: function(a, b) {
        return a + b;
    }
};

const numbers = {
    num1: 5,
    num2: 10
};

const result = mathOperations.add.call(numbers, numbers.num1, numbers.num2);
console.log(result);
You can also try this code with Online Javascript Compiler
Run Code


Output:

15

Example 2: Setting this to a Primitive Value

You can also use call() with primitive values, though this will still wrap them in their respective objects (e.g., String, Number).

const displayString = {
    show: function() {
        console.log(this.toString());
    }
};
displayString.show.call("Hello, world!");
You can also try this code with Online Javascript Compiler
Run Code


Output:

Hello, world!

Example 3: Using call() with Arguments

function multiply(a, b) {
    console.log(a * b);
}
multiply.call(null, 4, 5);
You can also try this code with Online Javascript Compiler
Run Code


Output:

20

Supported Browsers

The call() method is widely supported across all modern browsers, including:

  • Google Chrome
     
  • Mozilla Firefox
     
  • Safari
     
  • Microsoft Edge
     
  • Opera
     

It is also supported in Node.js, making it available for server-side JavaScript development.

Frequently Asked Questions

What is the difference between call() and apply()?

Both call() and apply() invoke a function with a specified this value, but they differ in how arguments are passed:

  • call(): Accepts arguments individually (e.g., call(thisArg, arg1, arg2)).
     
  • apply(): Accepts arguments as an array (e.g., apply(thisArg, [arg1, arg2])).

Can call() be used with arrow functions?

No, arrow functions do not have their own this context. The this value inside an arrow function is inherited from its surrounding scope, making call() ineffective in such cases.

Is the call() method exclusive to functions?

Yes, call() is a method of JavaScript functions and cannot be used with other data types.

Conclusion

The call() method in JavaScript is a versatile tool for invoking functions with a specified value. By understanding its syntax and applications, you can write more reusable and dynamic code. From borrowing methods to calculating areas of shapes, call() provides flexibility in programming. 

You can also check out our other blogs on Code360.

Live masterclass