JavaScript Interview Questions

23 Questions
JavaScript

JavaScript

Web DevelopmentFrontendBackend

Question 21

What is the difference between 'call' and 'apply' in JavaScript?

Answer:

Both 'call' and 'apply' are used to invoke functions with a specified 'this' value. The difference lies in how arguments are passed to the function: 'call' accepts a list of arguments, while 'apply' accepts a single array of arguments. These methods are useful for borrowing functions and setting the context for the 'this' keyword.

Here is an example demonstrating the difference between 'call' and 'apply':

function greet(greeting, punctuation) {
    console.log(greeting + ', ' + this.name + punctuation);
}

let person = { name: 'John' };

// Using call
greet.call(person, 'Hello', '!'); // 'Hello, John!'

// Using apply
greet.apply(person, ['Hi', '.']); // 'Hi, John.'

In this example, the greet function is called with different contexts using call and apply. The call method passes arguments individually, while the apply method passes arguments as an array.

Recent job openings