What is Function.call in JavaScript?

The call method calls the function with a given this value and arguments.

Syntax

call(thisArg, arg1, ... , argN)
  • thisArg: The this value on executing the function. It is an optional argument. However, if thisArg is skipped, the this value is:

    • non-strict mode - global object
    • strict mode - undefined
  • We can pass any number of arguments to the function after the thisArg argument.

  • The call method returns the value returned by the function.

Example

var number = 10;

function test(num1) {
  num1 = num1 ? num1 : 0;
  return this.number + num1;
}

console.log("Calling without thisArg");
console.log( test.call() ); // 10

let obj = {number :  20};
console.log("Calling with thisArg");
console.log( test.call(obj));  // 20

console.log("Calling with thisArg and arguments");
console.log( test.call(obj, 100) );  // 120

In the above code, we have created a test function that will return the sum of number property in the this object and the argument passed.

  • First, we called the test function using the call method without the thisArg argument. The global object is considered as this.

  • Then, we called the test method by passing obj as thisArg. Inside the test function, obj is considered as thisArg.

  • Lastly, we passed thisArg and argument to the test function.

Example with strict mode

"use strict" // strict mode
var number = 10;

function test(num1) {
  num1 = num1 ? num1 : 0;
  return this.number + num1;
}

console.log("Calling without thisArg");
console.log( test.call() ); // error

In the above code, we have called the test function without thisArg. This will result in an error because in strict mode, if we don’t pass the thisArg to the call function, then the this value inside the function is undefined. When trying to access the this value(undefined), we will get an error.

Free Resources