Introduction
When it comes to programming, the terms "call" and "invoke" are often used interchangeably to refer to executing a function. However, there is a subtle difference between the two terms. In this article, we will explain the difference between calling a function and invoking a function.
What is Calling a Function in JavaScript
When you call a function, you are passing control to the function. The function will execute and then return control back to the caller. When you "call" a function, you are simply executing the function. All you need is the function's name and appropriate arguments. For example, let's say you have a function named "add" that takes two arguments and returns the sum of those two arguments. You could call that function like this:
function add(arg1, arg2) {
return arg1 + arg2;
}
let result = add(5, 10);
console.log(result);
Output:
15
So, if you create a function and directly access and execute the function, you are calling the function.
What is Invoking a Function in JavaScript
In contrast, when you "invoke" a function, you are executing the function and also specifying the context in which the function will run. In other words, when you invoke a function, you are calling the function and also specifying the value of this inside the function. The context is the value of the "this" keyword inside the function. For example, let's say you have an object named "car" with a property named "color". You could invoke a function to set the color of the car like this:
car.setColor("red");
In this example, the "this" keyword inside the "setColor" function will refer to the "car" object.
To understand it better, let's make use of built-in methods and functions within JavaScript. Arrays have different methods (which are functions) that we can use with them, and when we make use of them, we are invoking the said function. For example, we are invoking the push
function because we are specifying the context in which the function/method will run (in reference to the arr
).
let arr = [1, 34, 212, 12];
arr.push(34);
console.log(arr);
Output:
[ 1, 34, 212, 12, 34 ]
Summary
So, to recap, the main difference between calling and invoking a function is that when you invoke a function you are also specifying the context in which the function will run.
References
Functions - JavaScript | MDN (mozilla.org)