Showing posts with label Advanced-Call and Apply. Show all posts
Showing posts with label Advanced-Call and Apply. Show all posts

Wednesday, May 9, 2018

Difference between Call and Apply


1. The call method always expect comma separated parameters.

2. The apply method always expect array of arguments.

3. However, call and apply both expecting object as first parameter.

Note:

In ES6, we know spread operator ... and you can pass an array (or any iterable) as a list of arguments.

So using this spread with call, almost you are achieving apply concept.


1
2
3
4
let args = [1, 2, 3];

func.call(context, ...args); // pass an array as list with spread operator
func.apply(context, args);

From the above code you can find some minor difference, let see what is that

1. The spread operator ... is iterable args.

2. The apply accepts only array-like args.

So an iterate is possible with call and it works.  Whereas we expect an array-like, apply works.

Generally apply will be faster because of its single operation.

func.apply

Already we saw about call and its expecting comma separated parameters. But in apply we should pass array arguments.

A simple example,


1
2
3
4
5
6
7
8
9
function say(time, phrase) {
  alert(`[${time}] ${this.name}: ${phrase}`);
}

let user = { name: "John" };

let arrayData = ['10:00', 'Hello'];

say.apply(user, arrayData); 

Explanation :

1. We are using apply at line no 9. Here user is our context and arrayData is array arguments for this apply.

2. In the arrayData 10:00 will be considered as time and phrase will be considered as Hello.

3. After executing lie no 9 control moves to line 1 to execute a method say and will print the output.


func.call

Its a built-in function method func.call(context, …args) that allows to call a function explicitly by setting this.

The syntax is


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

A simple example is below,


1
2
3
4
5
6
7
function say(phrase) {
  alert(this.name + ': ' + phrase);
}

let user = { name: "JavaScript" };

say.call( user, "Hello" ); // Javascript: Hello

Explanation :

1. In line no 7, we have used user as our context and Hello as our argument.

2. You can pass multiple parameters like arg1, arg2 etc.,

3. After executing line no 7, control will move to line no 1 and say method will be executed.


Things to Remember :

Generally, most of the people will get ambiguous for call and apply. To remember this, use mnemonic is "A for array(apply) and C for comma (call).