JavaScript Object Methods


Objects in JavaScript are collections of key/value pairs. The values can consist of properties and methods, and may contain all other JavaScript data types, such as strings, numbers, and Booleans.

All objects in JavaScript descend from the parent Object constructor. Object has many useful built-in methods we can use and access to make working with individual objects straightforward. Unlike Array prototype methods like sort() and reverse() that are used on the array instance, Object methods are used directly on the Object constructor, and use the object instance as a parameter. This is known as a static method.

This tutorial will go over important built-in object methods, with each section below dealing with a specific method and providing an example of use.

Accessing Object Methods

You access an object method with the following syntax:

objectName.methodName()

You will typically describe fullName() as a method of the person object, and fullName as a property.

The fullName property will execute (as a function) when it is invoked with ().

This example accesses the fullName() method of a person object:

name = person.fullName();

Example -

Using Built-In Methods

This example uses the toUpperCase() method of the String object, to convert a text to uppercase:

var message = "Hello world!";
var x = message.toUpperCase();

The value of x, after execution of the code above will be:

HELLO WORLD!

Adding a Method to an Object

Adding a new method to an object is easy:

Example

person.name = function () {
  return this.firstName + " " + this.lastName;
};

Example -