JavaScript Object

Objects are containers that can store data and functionality. JavaScript Object is a data type, nearly everything in JavaScript is an object. Objects store values using key and value pair. They key and value pair will have a colon : to link them. Multiple key and values pairs are separated using a comma.

 

Syntax for creating Object:

Following are different ways of creating an object.

Syntax 1 below is using an Object constructor

var myObjectName = new Object();

OR
let myObjectName = new Object();

Syntax 2 below is using an Object literal, this is preferred way of creating objects.

var myObjectName = {};
OR
let myObjectName = {};

  • myObjectName can be any name of your choice.
  • The parentheses ( ) and the curly brackets { } can save multiple keys and values of an object.
  • Object values are separated by commas.
  • Object values can be text, html, code, string, functions or pretty much anything.

Syntax for creating Object with properties and methods:

let myObjectName = {
propertyKeyName1 : value,
propertyKeyName2 : value,
propertyKeyName3 : value,
methodKeyName4 : function(){ //method definition goes here},
methodKeyName5 : function(){ //method definition goes here}
};

Syntax for accessing Object members:

  • Object properties can be accessed using object name dot property name myObjectName.propertyKeyName;
  • Object methods can be accessed using object name dot method name myObjectName.methodKeyName();

Example of JavaScript Objects

  • In above example, we have created an object named house.
  • This object has three properties created using key : value syntax
  • This object has one method price defined using key: value syntax. The method is created using a function keyword.
  • We can access the properties of the object using dot notation, the syntax is object.property. In above example, we have achieved that by house.rooms and house.city
  • We can access the methods of the object using dot notation, the syntax is object.method(). In above example, we have achieved that by house.price();

Objects vs Arrays:

  • Objects like arrays can store multiple data.
  • Usually we use arrays to store indexed data and we use objects to store data that doesn’t have to be indexed. For example, when we want to store all the product names an array would be useful. However, when we want to store products name and price we can use objects.
  • Arrays are good for using ordered data and objects for data that can be referenced using their name rather than positions.
  • Objects are like associative arrays where each value has a key (key can be string. In Array, each value has a number (position).