Hackernoon logoUsing apply() in javascript by@trekinbami

Using apply() in javascript

Sam Pakvis Hacker Noon profile picture

Sam Pakvis

Creative React/Javascript developer

After writing about bind() and call(), this article will explain more on apply(). Those articles cover some stuff, especially about this and context, which is pretty important. So if you havenโ€™t read those articles already, I really recommend you do so.

Just like bind and call, apply() changes the context of this in the function you apply it to. If you want to know more about changing the context of this, I recommend you to read my previous articles on bind and call.

Apply does the exact same thing as call(), but with one subtle difference. Its second argument is an array of arguments, instead of the individual comma based arguments that call() requires. The first argument is, just like withcall(), the new context of this.

The comments kinda speak for themselves. But for clarity: weโ€™re executing callOut, changing the context of callOut, and passing an Array as the single argument for apply(). You can, of course, use a million other ways to achieve the same result, but this was a short example to show you everything apply() has to offer.

And thatโ€™s it. Thanks for reading! Any questions? Reply, or send me a message on Twitter: http://twitter.com/trekinbami


Join Hacker Noon

Create your free account to unlock your custom reading experience.