New Tutorials:   TKINTER    KOTLIN    JAVASCRIPT    SASS/SCSS    PL/SQL
See the Tutorial List

JavaScript Objects

In JavaScript, we can define an object as a collection of properties that are defined as a key-value pair, where the key is the generic name of the object feature which can be assigned a value. Don't confuse this object with class objects, where we define a class and then create an object for it.

In JavaScript, an object is a standalone entity where the properties of the object define the characteristics of the object.

For example, if we consider a mobile phone as an object then its properties are its color, screen size, brand name, operating system, RAM, Memory, etc. All these properties define the characteristics of a mobile phone.

The property of an object is a key:value pair, where key refers to a variable, and value refers to any type of value associated with the key. The value can be of any type like a number, string, or even an array, or another object.

We can create an object in JavaScript either by using the constructor function or the object literal.

Creating a JavaScript Object

We can create a JavaScript object either by using the Object constructor or using the object literal syntax. Below we have the basic syntax for creating an object is JavaScript using both ways:

/* Using Object constructor */
let obj1 = new Object();
/* Using the object literal syntax - empty object */
let obj2 = {};
/* Using the object literal syntax - with properties */
let obj3 = { key1:value1, key2:value2, ...};

When we create an object using the Object constructor, we first create an empty object and then assign properties to it while in case of the object literal syntax, we can create an empty object or specify properties within the curly braces while creating an object.

No need to get confused, JavaScript provides with multiple different ways for creating objects. Let's take a few examples to cover different ways of creating objects in JavaScript.

JavaScript Object Using Object Constructor

We can create a direct instance of an object by using the new keyword:

let mobile = new Object();

and then can assign properties to it using the dot operator(.) as shown below:

mobile.name = 'Blackberry';
mobile.color = 'Black';
mobile.price = 40000;

We can also create the object and assign properties to it in a single go like this,

let mobile = new Object(),
             color = 'Black',
             price = 40000,
             specifications = new Object();

As you can see in the code example above, our object has a property which is also an object.

JavaScript Object Using Object Literal Syntax

To create an object using object literal syntax, we use curly brackets { }. It is the preferred way and simpler way too, but do the same as Object constructor. We can define properties of this object inside the curly brackets.

Let's create an object, mobile phone that has color, name, price as its properties.

let mobile = {         
    name: "Apple iPhone",
    color: "Black",
    price: 100000      
};

In the mobile object, there are three properties:

  1. The first property has the key name and the value "Apple iPhone".

  2. The second one has the key color and the value "Black".

  3. The third property has key price and the value 100000.

Accessing JavaScript Object Property

To get the property of an object, we can use the dot(.) operator followed by the property name or key. See the below example,

It doesn't matter how you create the object, the way of accessing the property will remain the same.

Using Square Bracket Notation:

We can also use the square bracket notation for accessing any property using the property name or key. A JavaScript object is similar to an associative array, because an associative array also has named index value unlike the numeric index values in a simple array.

Let's take an example to see how we can use the square bracket notation to access object properties:

/* JS comes here */
let mobile = {         
    name: "Samsung",
    color: "black",
    price: 40000      
};

// Accessing property using square brackets
document.write(mobile['name']);
document.write("<br>"+mobile['color']);

Just like we access a property value, we can also add a new property to an object.

Add new Property to JavaScript Object

JavaScript allows us to add a new property to an existing object. See the below example:

let mobile = {         // an object
  name: "BlackBerry",  // property
  color: "black",
  price: 40000      
};


// Adding New Property
mobile.weight = "100gm"

// Accessing newly added property
document.write(mobile.weight)


100gm

Using Square Bracket Notation:

We can also use the square bracket notation for setting any property using the property name or key.

Let's take an example to see how we can use the square bracket notation to access object properties:

/* JS comes here */
let mobile = {         
    name: "Samsung",
    color: "black",
    price: 40000      
};

// setting property using square brackets
mobile['screen'] = "5 in";

Remove Property of a JavaScript Object

If we want to remove any property from the object, then we can do it easily by using delete operator. See the below example:

let mobile = {         // an object
  name: "BlackBerry",  // property
  color: "black",
  price: 40000      
};


// Deleting Property
delete mobile.price;

// Trying to access deleted property
document.write(mobile.price);   // Undefined


Undefined

Update Property of a JavaScript Object

Updating a JavaScript object property value with a new one is allowed. To update any property, just assign it a new value. See the below example:

let mobile = {         // an object
  name: "BlackBerry",  // property
  color: "black",
  price: 40000 
};


// Updating property 
mobile.color = "Pearl White";

// Accessing Property
document.write(mobile.color);


Pearl White

JavaScript Object: Handling Multiword Property

JavaScript allows us to create multiword property but with little care because accessing multiword property using dot(.) operator will produce a syntax error. So, to avoid this error, we should use square brackets ([]).

Let's take an example to see this:

let mobile = {         // an object
  name: "BlackBerry",  // property
  color: "black",
  "latest price": 40000      // multiword should enclose with double quotes
};

// setting multiword property key-value with square brackets
mobile["screen size"] = "5 in";


// Accessing Property using square brackets
document.write(mobile["latest price"]);


40000

If we will try to access a multiword key property using the dot operator (.) we will get a syntax error.

Traversing JavaScript Object

We can traverse the object's properties by using for-in loop. It returns keys associated with object that further can be used to fetch values. See the below example:

let mobile = {         // an object
  name: "BlackBerry",  // property
  color: "black",
  price: 40000
};


// Traversing object
for (key in mobile) {
	document.write(mobile[key]+"<br>")
}


BlackBerry
black
40000

Creating Method in JavaScript Object

We can also define methods in an object. A method is a function associated with an object. Methods are defined just as normal JavaScript functions are defined, except that they have to be assigned to an object as a property.

Defining the JavaScript Object Method:

Here, we are defining a method showInfo that will display the information about the object, i.e. all the object properties.

let mobile = {         // an object
    name: "BlackBerry",  // property
    color: "black",
    price: 40000

    // defining method
    showInfo: function() {
        document.write(this.name+" "this.color+" "+this.price);
    }
};

Accessing the JavaScript Object Method:

Accessing or calling a method is pretty easy, just use dot(.) operator with object name:

var mobile = {         // an object
    name: "BlackBerry",  // property
    color: "black",
    price: 40000,

    // method
    showInfo: function() {
        document.write(this.name+" "+this.color+" "+this.price)
    },
};

// Calling method
mobile.showInfo();


BlackBerry black 40000

JavaScript Built-in Objects

JavaScript has rich set of built-in objects that can be used to deal with various types of collections. Some commonly used built-in types are listed below.

  1. String

  2. RegExp

  3. Boolean

  4. Number

  5. Array

  6. Math

  7. Date

In the next few tutorials, we will cover the built-in JavaScript objects and we will also learn how we can create custom user-defined objects in JaavaScript.