🎄JS Advent #4 - call() and apply() 🎄

jtlavs

James L

Posted on December 4, 2022

🎄JS Advent #4 - call() and apply() 🎄

For the month of December I have challenged myself to write 24 articles about JS up until Xmas.

The fourth installment in this series is about call() and apply().

The call() function

  • The call method calls a function. It takes a this value as its first parameter and then optional arguments as a list for each parameters of that function.

Example:

//globalThis
x = 2; y = 3;

const obj = {
    x: 10;
    y: 20;
}

function add () {
    return this.x + this.y;
}

console.log(add.call(obj)); // 30

// 5 - globalThis is used (However in strict mode globalThis is not substituted so it would return NaN)
console.log(add.call());
Enter fullscreen mode Exit fullscreen mode
  • Passing parameters as a list:
// globalThis
x = 2; y = 3;

const obj = {
    x: 10;
    y: 20;
}

function add (a, b) {
    return this.x + this.y + a + b;
}


console.log(add.call(obj, 20, 30)); // 80

// 55 - as null or undefined is converted to the globalThis object in non strict mode
console.log(add.call(null, 20, 30)); 
Enter fullscreen mode Exit fullscreen mode

The apply() function

  • The apply method operates almost exactly the same as the call method except that it takes an array of parameters instead of as a list.

Example:

// globalThis
x = 2; x = 3;

const obj = {
    a: 10;
    b: 20;
}

function add (a, b) {
    return x + y + this.a + this.b;
}


console.log(add.apply(obj, [20, 30])); // 80
console.log(add.apply(null, [20, 30])); // 55
Enter fullscreen mode Exit fullscreen mode

< JS Advent 3 - Object.hasOwnProperty()

💖 💪 🙅 🚩
jtlavs
James L

Posted on December 4, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

How JavaScript works
javascript How JavaScript works

November 8, 2024

A Beginner's Guide to JavaScript Closures
javascript A Beginner's Guide to JavaScript Closures

November 5, 2024

Type Coercion in JavaScript Explained
javascript Type Coercion in JavaScript Explained

November 18, 2024

Introduction to Asynchronous JavaScript
javascript Introduction to Asynchronous JavaScript

October 14, 2024

Strings -- Manipulating the Immutable.
javascript Strings -- Manipulating the Immutable.

November 15, 2024