I am Hack Sparrow
Captain of the Internets.

JavaScript – .apply and .call

Apply and Call in JavaScript

Maybe you have heard about them, maybe you are new to them, but the apply and call JavaScript functions are one of the less encountered and less well understood aspects of JavaScript - primarily because of their unfamiliarity. Why are they unfamiliar?

Most of the learning materials (tutorials and books) available for JavaScript tend to teach JavaScript in the C/Java mindset. Most JavaScript beginners endeavor to find out the closest C/Java equivalents in JavaScript and assume that they have covered everything JavaScript has to offer as a programming language.

They almost always miss an amazing aspect of JavaScript - it is also a functional programming language. There is no sensible equivalent of that aspect in C/Java. It is a completely different programming paradigm. You probably would have no idea what that means unless you have programmed in Common Lisp, Scheme, Haskell, and other functional programming languages. Apply and Call are two of the functional aspects of JavaScript. JavaScript as a functional programming language is a topic for another post, for now let's see what Apply and Call are.

It may sound very strange, but apply() and call() are functions of functions. Not making sense? Then try this: all JavaScript functions have two functions called apply() and call() (there is another called toString()). If you didn't know, everything in JavaScript is an object, even functions are objects, hence they can have properties and functions. Functions attached to an object is technically called a method, so it is technically more correct to say apply() and call() are methods of functions.

I want to show you what apply() and call() are and what they do by the means of an example. Load the following code in a browser or execute it using Node.js.

var type = 'mermaid'
var name = 'Ariel';
var sound = 'sing';

function vocalize(quality) {
console.log(this.name +' '+ this.sound +'s '+ quality);

function act(when, why) {
console.log(this.name +' is a '+ this.type +' who '+ this.sound + 's ' + when +' '+ why);

act('every day', 'because she wants to see the world outside');

Everything working as expected? Now append the following code to the script and run it again:

var dog = {type:'dog', name:'Pluto', sound:'bark'};
var cat = {type:'cat', name:'Kiddo', sound:'meow'};
var cow = {type:'cow', name:'Mabel', sound:'moo'};

vocalize.call(dog, 'loudly');
vocalize.call(cat, 'happily');
vocalize.call(cow, 'slowly');

act.apply(dog, ['at night', 'because he is angry']);
act.apply(cat, ['in the morning', 'because he is sleepy']);
act.apply(cow, ['in the afternoon', 'because she is hungry']);

Analyse the result and see if it makes sense to you, or if you can make any sense out of it.

Notice how the functions vocalize() and act() aren't actually hard-wired to anything? When you first executed the script it might have looked like the functions were hard-wired to the this (the window / process object in that case) object, but then it turned out that the functions can be used by other objects as effectively. Isn't that a drastic paradigm shift from OOP? In OOP you have objects with tightly bound methods, in this case (functional programming) we have 'free-floating' functions that can be tapped by any object and use them as if they were truly their methods!

That is the magic of apply() and call(). They both can change the context of this and make functions usable by different objects. They allow you to execute functions as methods of different objects.

Does that give you any ideas? Could this approach make more sense than using the C++/Java style object-oriented paradigm in JavaScript? How can you effectively use apply() and call() in your next project?

So what's the difference between apply() and call()? If you have been observant enough, you should have noticed that apply() accepts an array of arguments and call() accepts a single string parameter, that's their only difference. Use call() on functions that accept a single parameter, use apply() on functions that accept multiple parameters.

You have tasted a tiny bit of functional programming. Did you like it? If yes, you should definitely check out functional programming, it will expand your mind. I kid you not.

One Response to “JavaScript – .apply and .call”

  1. Sandesh Magdum says:

    This is great tutorial. I learned many new functional aspects of javascript.

    Sandesh Magdum

Make a Comment