Javascript Tutorial
Javascript Tutorial Introduction to Javascript JavaScript Code Editors & IDE JavaScript Hello World Example Javascript Syntax and Rules syntax_rules javascript_identifiers JavaScript Keywords & Reserved Words javascript_variables JavaScript Const JavaScript let vs var vs const Data Types in JavaScript JavaScript String Template Literals & String interpolation in JavaScript Tagged Templates in JavaScript String to Number in JavaScript Number Data Type in JavaScript NaN in JavaScript JavaScript Number Min & Max & Safe Values JavaScript EPSILON & Floating point precision Infinity in JavaScript JavaScript Bigint BigInt Vs Number in JavaScript Boolean Data Type in JavaScript Undefined in JavaScript Null in JavaScript Null vs Undefined in JavaScript JavaScript Operators Arithmetic Operators in JavaScript Unary plus & minus operators in JavaScript Increment & Decrement Operators in JavaScript Comparison or Relational operators in JavaScript Strict Equality (==) Loose Equality (===) in JavaScript Ternary Conditional Operator in JavaScript Logical Operators in JavaScript Bitwise Operators in JavaScript Assignment Operators in JavaScript Nullish Coalescing Operator in JavaScript Comma Operator in JavaScript Typeof JavaScript Operator Precedence in JavaScript JavaScript if, else & nested if statement Switch Statement in JavaScript While & Do While Loops in JavaScript For Loop in JavaScript Break statement in JavaScript Continue Statement in JavaScript Arrays in JavaScript Array Constructor in Javascript Sparse Array Vs Dense Array in JavaScript How to merge Arrays in JavaScript Array Methods in JavaScript Functions in JavaScript Function Parameters & Arguments in JavaScript JavaScript Default Parameters Pass by Value and Pass by Reference in Javascript Function Expression in Javascript Nested Functions in JavaScript Immediately-invoked Function Expressions (IIFE) JavaScript Callback Functions Arrow Functions in JavaScript Arguments Object In JavaScript Rest Parameters in JavaScript Objects in Javascript Create Objects in JavaScript JavaScript Object Properties Computed Property Names in JavaScript Object Literal in JavaScript Constructor Function & New Operator in JavaScript Delete Operator in JavaScript hasOwnProperty in JavaScript Using Getters and Setters in Javascript DefineProperty in JavaScript JavaScript Property Descriptors Enumerable, Writable & Configurable Object Destructuring in JavaScript Variable Scope in JavaScript Hoisting in JavaScript Lexical Scope & Closures in JavaScript This in JavaScript Global Object, Window & Globalthis in JavaScript Call function in Javascript Prototype In Javascript Prototype Inheritance in JavaScript Instanceof Operator in JavaScript Spread Operator in JavaScript

Call function in JavaScript

The call() function is a built-in function in JavaScript that allows you to call a function with a specified “this” value. This tutorial lets us learn more about JavaScript’s call() function.

“this” in Javascript

“this” in JavaScript is an object. Every JavaScript function gets a copy of this (except arrow functions). Its value does not depend on where we declare it but on how we invoke it. You can read more about from the article this in javascript.

The call function is one of the ways we set the “this” of a function.

Syntax

The syntax of the call function is as follows

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

Here, func is the function that you want to call.

thisArg is the object you want to use as this value in func.

arg1, arg2, etc., are the arguments you want to pass to the function func.

The call function returns whatever is returned by the function func.

Call function Examples

The following is an example of using the call() function to call a function.

The code sayHello.call(person); sets the person as the this inside the sayHello function and invokes it.

            
function sayHello() {
  console.log(`Hello, ${this.name}.`);
}
 
const person = {
  name: 'John'
};
 
sayHello.call(person);  //Hello, John.
 
                
        
    

If we invoke sayHello() directly (without call), then the “this” inside the sayHello is bound to the global object in “not strict” mode. But if we use the “strict” mode, “this” is always null.

            
sayHello() //Hello, undefined.
 
                
        
    

The following example shows how you can pass parameters using the call function.

The sayHello function below accepts a parameter, which we pass as the second argument to the call function.

            
function sayHello(name) {
  console.log(`Hello, ${this.name}. my name is ${name}`);
}
 
const person = {
  name: 'John'
};
 
sayHello.call(person,"Mike");  //Hello, John. my name is Mike
 
                
        
    

The add function accepts two arguments. The code shows how to invoke the add function using the call function.

            
function add(a, b) {
  return a + b;
}
 
// invoking add() by passing this and 'a', 'b' arguments 
let result = add.call(this, 10, 20);
console.log(result);    //30
 
//calling add directly
result = add(10, 20);
console.log(result);    //30
 
                
        
    

Borrowing methods from another object

We can use the call function to invoke methods from other objects.

The john object in the following code contains the method greet, and the mike object does not.

We can take the greet method from the john object, set its this to mike, and invoke it (john.greet.call(mike)).

            
 name: 'John',
  age: 50,
  greet: function() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
};
 
const mike = {
  name: 'Mike',
  age: 40
};
 
john.greet()   
//Hello, my name is John and I am 50 years old.
 
john.greet.call(mike)
//Hello, my name is Mike and I am 40 years old.
                
        
    

Chaining Constructors

Constructor chaining is a technique where a constructor function calls another constructor function. Using this technique, we can create an inheritance relationship between two or more constructor functions, where one constructor function “inherits” properties and methods from another.

For example, think of Employee & Customer objects. Both of these objects have common fields like name & address.

What we do is create a Person constructor function with the common fields. And in the Employee & Customer constructor functions, invoke the Person constructor, passing “this” value.

            
function Person(name,address) {
  this.name = name;
  this.address=address;
}
 
function Employee(name, address,Designation) {
  Person.call(this, name,address);
  this.Designation = Designation;
}
 
function Customer(name, address, creditDays) {
  Person.call(this, name,address);
  this.creditDays = creditDays;
}
 
 
let e = new Employee("John","Newyork","CEO")
let c = new Customer ("Mike","Washingtom",30)
 
console.log(e)
//Employee { name: 'John', address: 'Newyork', Designation: 'CEO' }
console.log(c)
//Customer { name: 'Mike', address: 'Washingtom', creditDays: 30 }
                
        
    

Array-like objects

Array-like objects are objects that look like arrays but are not arrays. For example, the numbers object below is an object with numerical indexes as property names and has a length property.

We cannot run the array method on them directly. But use the call function to invoke their array methods like sort, filer, split, etc on array like objects.

The code below sorts the numbers object using the Array sort method.

            
 const numbers = {
    0:1,
    1:300,
    2:7000,
    3:2000,
    4:21,
    5:5 ,
    length:6
}
    
Array.prototype.sort.call(numbers,(a,b) => a -b);
console.log(numbers);
//{ '0': 1, '1': 5, '2': 21, '3': 300, '4': 2000, '5': 7000, length: 6 }
                
        
    

Summary

  1. The call() function invokes any function with a specified “this”value.
  2. The value of “this” is passed as the first argument of the call function.
  3. We pass the function’s arguments as subsequent arguments to the call function.