How to call a Function inside an Object in JavaScript

avatar

Borislav Hadzhiev

Tue Nov 16 20212 min read

banner

Photo by Kevin Laminto

Call a Function inside an Object in JavaScript #

You can call a function inside an object by declaring the function as a property on the object and invoking it, e.g. obj.sum(2, 2). An object's property can point to a function, just like it can point to a string, number or other values.

index.js
const obj = { sum(a, b) { return a + b; }, }; console.log(obj.sum(10, 10)); // ๐Ÿ‘‰๏ธ 20 console.log(obj.sum(10, 20)); // ๐Ÿ‘‰๏ธ 30

We declared a sum property on an object. The property points to a function.

index.js
const obj = { sum(a, b) { return a + b; }, }; console.log(typeof obj.sum); // ๐Ÿ‘‰๏ธ "function"

To call the function, we can access the object property using dot . or bracket [] notation and invoke the function using parenthesis.

We used the shorthand property to define the function in the object.

When reading older code, you might see this more verbose and outdated approach being used:

index.js
const obj = { sum: function (a, b) { return a + b; }, }; console.log(obj.sum(10, 10)); // ๐Ÿ‘‰๏ธ 20 console.log(obj.sum(10, 20)); // ๐Ÿ‘‰๏ธ 30

The first approach is more concise and easier to read.

You can access properties on the object inside of the function, by using the this keyword.

index.js
const obj = { num: 100, sum(a, b) { return a + b + this.num; }, }; console.log(obj.sum(1, 1)); // ๐Ÿ‘‰๏ธ 102

In this particular context, the this keyword refers to the object.

You could also add a function to the object after it the object has been declared.

index.js
const obj = { num: 100, }; obj.sum = function (a, b) { return a + b + this.num; }; console.log(obj.sum(10, 10)); // ๐Ÿ‘‰๏ธ 120

Notice that we used the function keyword to define the function. Had we used an arrow function, the value of the this keyword would not be correctly bound and would point to the enclosing scope (not the object).

index.js
const obj = { num: 100, }; obj.sum = (a, b) => { console.log(this); // ๐Ÿ‘‰๏ธ {} return a + b + this.num; }; console.log(obj.sum(10, 10)); // ๐Ÿ‘‰๏ธ NaN

This is irrelevant in most cases, as you very rarely have to use the this keyword with objects, but this also applies to classes.

Arrow functions don't have their own this keyword like named functions do. Instead arrow functions use the this context of the enclosing scope.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee