How to call a JavaScript function

Of course, every developer knows how to call a JavaScript function - it's just a basic thing. But bear with me, I will share some additional information about calling a function. (psst! do you know how func() == func becomes true in JavaScript?)

Let's say that we have a simple JavaScript function foo that takes two parameters and prints out some information to the console. Notice that inside the function, we access the this object as well.

// define a global variable `name`
window.name = "Global";
function foo(param1, param2) {
  console.log("Hello world", this.name, param1, param2);
}

1. Call a function using ()

foo(1, 2); // Hello world Global 1 2

This is straight forward - call a function by its name followed by two parenthesis() with the arguments passed. Notice that when you call a function this way, the reference this inside the function, points to the global/window scope. Hence, this.name prints Global on the console.

2. Call a function using call

Now what if you want to change the context while calling a function, so that instead of this referring to the global context, it can refer to anything that you wish.

foo.call({ name: "called" }, 1, 2); // Hello world called 1 2

Using call method, you can pass in the custom context as the first parameter. Now, this will refer to this first parameter inside the called function. So, this.name will become "called", instead of "Global". Following the first parameter, you can pass additional parameters one by one, as usual.

3. Call a function using apply

Now you learned how to change the context when calling a JavaScript function. But it becomes cumbersome to pass the parameters to call method one by one. What if you have an array of values that you want to pass to a function as individual parameters? You can do so with apply method.

foo.apply({name: 'applied'}, [1,2]); // Hello world applied 1 2

apply takes the second parameter to pass it down to the called function one by one as you would have done when calling a function directly. Sweet!

But why would we want to do that? Well, here's a real word use case.

Let's say you have an array of numbers, and you want to find the minimum of these numbers. You know that JavaScript has a built-in function Math.min that returns the minimum of given arguments - but it accepts arguments as separate parameters, not as an array. With what we learned, we can reuse the min method as below.

const numbers = [8, 7, 9, 1, 4];
const minimum = Math.min.apply(Math, numbers); // 1

Handy, isn't it?