Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

What is right way to use CALL and APPLY ()

How to use CALL(). When to use it.

I know apply(valueforTHIS, [arrg, argg,..]) takes value and array of arguments, that makes it different from CALL. But What is the benefit of both of them.

Can you please explain me with a practical example! :)

Thank you.

2 Answers

Ajinkya, this main difference between call() and apply() is that call requires a list of arguments and apply accepts an array of arguments. So if you create a function like this:

function concat( a, b, c){
    console.log(a+" "+b+" "+c);
}

you would need to use call, because the function accepts a set number of value ( a, b, c). Now if the function was written like this:

function concat(array){
    var string;
    for (x in array){
        string += x+" ";
    }
    console.log(string);
}

where the function accepts an array as an argument then you would need to use apply.

The important thing to remember with call and apply is how are the arguments passed into the function. If they are a list ( separated by commas) then use call. If they are an array or object then use apply. For more information checkout call and apply

Hi, Andrew Shook Thanks for reply. Yes I eventual ended at MDN link. Also found this http://odetocode.com/blogs/scott/archive/2007/07/04/function-apply-and-function-call-in-javascript.aspx

Also I wanted to know more example where we can practically use them.