Javascript Function call()

The call() method calls a function by passing this and specified values as arguments.

Example


call() Syntax

The syntax of the call() method is:

func.call(thisArg, arg1, ... argN)

Here, func is a function.


call() Parameters

The call() method can take two parameters:

  • thisArg - The thisArg is the object that the this object references inside the function func.
  • arg1, ... argN (optional) - Arguments for the function func.

Note: By default, in a function this refers to the global object i.e, window in web browsers and global in node.js.


call() Return Values

  • Returns the result obtained from calling the function with the specified this value and arguments.

Note: By using call(), we can use the functions belonging to one object to be assigned and called for a different object.


Example 1: Using call() Method

Output:

8

In the above example, we have defined a function sum() that returns the sum of two numbers.

We have then used the call() method to call sum() as sum.call(this, 5, 3).

Here, by default, the this inside the function is set to the global object.


Example 2: With and Without Using call() Method

Output:

Return value Without using call() method: 10
Return value Using call() method: 10

In the above example, we have called the product() function: without using call() and using call().

  • Without using call()- we can directly invoke product() as product(5, 2).
  • Using call()- we have to pass this argument as product.call(this, 5, 2).

Example 3: Passing Object as this Value in call()

Output

My name is Judah Parker. I am 26 years old.

In the above example, we have defined the greet() function inside which we have defined a variable string that can access the values of human.

We have then passed the human object as this value in the call() method as greet.call(human), which calls greet().


Example 4: Using call() to Chain Constructors

Output

Harry 5 Hiss
Arnold 8 Neigh

Note: The difference between call() and apply() is that call() accepts an argument list, while apply() accepts a single array of arguments.


Recommended Reading: JavaScript Function apply()