Recently I wrote post on What is Bind method in JavaScript and about What is call() method in JavaScript In this post we will take a look on apply method in JavaScript.

apply() method is exactly the same as call() method with minor difference in passing arguments.

Alike call() method using apply() method also, you can invoke a function on given object. Let us understand with some example. Consider that you have a function GreetingMessage() as following ,


function GreetingMessage() {

alert("Hello Geek !");
 };

And you have an object Student as following,

var Student = {};

You can call function GreetingMessage on object Student as following,

GreetingMessage.apply(Student);

As output you should get following output,

clip_image001

Apply() method allows you to invoke function which parameter is array of not fixed length. Apply() method pass arbitrary length array as arguments to function.

Let us consider following example. In below example we are calculating sum of the array in function FindSum().


function FindSum(e) {

var sum = 0;
 for (var i = 0 ; i < arguments.length ; i++) {

sum = sum + arguments[i];

}
 return sum;
 };

var Student = {
 };


var sumOfMarks = FindSum.apply(Student, [12, 45, 11, 56, 189]);
 alert(sumOfMarks);

Essentially above you are passing dynamic array to apply method. In function you can access passed parameters using arguments. As output you will get sum of passed array,

clip_image001[6]

To summarize,

  • apply() method takes at least one parameter.
  • First parameter is object on which function to be invoked
  • Second parameter onwards get passed to the function to be invoked.
  • It passes arbitrary length array to function

This was a brief discussion of apply() method is JavaScript. I hope you find this post useful. Thanks for reading.

Advertisements

4 thoughts on “What is apply() method in JavaScript

  1. your images are broken, so we can’t see the outputs. why not put them in text and/or add the intended outputs to alt tags on the images?

  2. … Oh man, much better with images πŸ™‚ Really cool, just read your other 2 posts on .bind() and .call() and came here last. Short, clear and sweet πŸ™‚

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s