Using apply() in javascript

Written by trekinbami | Published 2016/10/18
Tech Story Tags: javascript | es2015 | programming | functional-programming | es6

TLDRvia the TL;DR App

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


Published by HackerNoon on 2016/10/18