Objects in JavaScript

In this section of the tutorial, we will discuss Objects in JavaScript and their uses with their different properties, i.e. key-value pairs that are used in the JavaScript program with some good examples for in-depth understanding.

What are Objects in JavaScript?

In JavaScript, Objects are known as the most fundamental type of data type. Objects are composite values that aggregate multiple values. Objects allow a user to store and retrieve such values by name.

  • An object is an unordered collection of properties that has a name and a value associated with it.
  • An object can inherit the properties of another object known as its prototype.
  • Objects in JavaScript are dynamic in nature.
  • Objects have properties that can usually be added and deleted and they can also be used to simulate the static objects and structs of statically typed languages.
  • Objects in JavaScript can also be used to represent sets of strings.
  • Any value in JavaScript that is not a string, a symbol, number, or true, false, null, or undefined is an object.
  • Values that are not object can still behave like immutable objects.

When we are talking about objects and their properties, we should be clear of the definition of the property.

A property can have a name and a value. The name of property may be any string or empty string or any symbol. However, no object having two properties can have the same name. Properties can be distinct, i.e. inherited or non-inherited or own properties.

Properties of an object in JavaScript can have three attributes associated with them:

  • Writable attribute – It specifies whether we can set the value of the property.
  • Enumerable attribute – It specifies for/in loop is used to return the property name.
  • Configurable attribute – It specifies whether we can delete the property and whether we can alter its attribute.

How to Create Objects in JavaScript?

Objects can be created using many different methods such as using object literals, using new, prototype method, and using object.create(). We will discuss each of these methods in detail in the section below.

Objects Literals

It is the easiest way out of all to create objects in JavaScript. An object literal is simply included in the code.

An object literal is a list of name:value pair separated by colons and commas, enclosed within curly braces.

We will take an example to know how we can create object using literals.

Example:

<html>
<head>
<title>JavaScript</title>
<script type="text/javascript">

let empty = {};
let point = { x: 0, y: 0 };
let p2 = { x: point.x, y: point.y+1 };

let book = {
    "main title": "CODEDEC",
    "sub-title": "Happy Learning",
    for: "for everyone",

    creator: {
        firstname: "Shahbaz",
        surname: "Ahmad"
    }
};

</script>
</head>
<body>
</body>
</html>
  • Here, in line 6, an object is created with no properties.
  • In line 7, an object point has numeric properties.
  • In line 8,  an object x has complex value in its properties.
  • In line 10 and 11, properties have name including spaces and hyphens, so string literals are used.
  • In line 12, the object for is reserved.
  • In line 13, the value of the object creator is itself an object.

Creating using new

We can also create objects in JavaScript using the new operator. The new operator creates and initializes a new object. The keyword new must be used followed by the function invocation. Such functions ae also called constructors.

We will take an example to understand how we can create an object using new operator.

Example:

<html>
<head>
<title>JavaScript</title>
<script type="text/javascript">

let o = new Object();
let a = new Array();
let d = new Date();
let r = new Map();

</script>
</head>
<body>
</body>
</html>

In the above example, several objects are created using the new operator.

By Prototype method

Prototype in JavaScript can be understood as second objects that inherit its properties to the first object in a program.

All objects created using object literals have the same prototype object which is known as Object.prototype in the JavaScript code.

We will take an example to understand the prototype method of creating an object in JavaScript.

Example:

When a new operator is used to create object new Object() in a JavaScript code. It inherits its properties from the second object from the Object.prototype just as the object created by {} does.

Similarly, when a new object is used to create object new Array(), it inherits its properties from its prototype Array.prototype.

By Object.create()

Another method of creating an object in JavaScript is by using Object.create() using its first argument as the prototype of that object.

We will take an example to understand how we can use Object.create() to create a new object in JavaScript.

Example:

<html>
<head>
<title>JavaScript</title>
<script type="text/javascript">

let o1 = Object.create{{x: 1, y: 2}};

o1.x + o1.y

let o2 = Object.create(null);
let o3 = Object.create(Object.prototype);

</script>
</head>
<body>
</body>
</html>
  • Here, in line 6, object o1 will inherit the properties of x and y.
  • In line 8, the expression will produce an output 3.
  • In line 10, o2 will no inherit any property or method.
  • In line 11, o3 is like {} or a new Object().

Setting and Querying of Properties

In JavaScript, we use a dot (.) operator or a square operator ([]) to access the value of a property.

  • The formal convention to write such an expression is to write the the expression whose value is an object on the left hand side.
  • When using the dot operator, we use a simple identifier that names the property on the right hand side.
  • When using the square operator, there must be a value inside the brackets that evaluates to a string that contains the desired name of the property.

We will take an example to understand the naming convention.

Example:

<html>
<head>
<title>JavaScript</title>
<script type="text/javascript">

let author = book.author;
let name = author.surname;
let title = book["main title"];

</script>
</head>
<body>
</body>
</html>

In order to create or set a property, we can use the dot or square operator in the left hand side of an assignment expression.

Example:

<html>
<head>
<title>JavaScript</title>
<script type="text/javascript">

let author = book.author;
let name = author.surname;
let title = book["main title"];

book.edition = 7;
book["main title"] = "JavaScript Book"

</script>
</head>
<body>
</body>
</html>

Objects and Associative Arrays

From what we have discussed earlier, it is clear that expressions object.property and object[“property”] have the same values.

Also, when we want to access a property of an object with [] brackets or array notation, the name of the property is expressed as a string.

Example:

<html>
<head>
<title>JavaScript</title>
<script type="text/javascript">

let addr = "";
for (let i = 0; i < 4; i++) {
    addr += customer['address${i}'] + "\n";    
}

</script>
</head>
<body>
</body>
</html>

In the above code, the loop will iterate and concatenate the address0, address1, address2, and address3 properties of the customer object.

JavaScript Objects are commonly used as associative arrays.

We will take an example to understand how an object is used as associative arrays and how it works.

Example:

<html>
<head>
<title>JavaScript</title>
<script type="text/javascript">

function computeValue(portfolio) {
    let total = 0.0;
    for( let stock in portfolio) {
        let shares = portfolio[stock];
        let price = getQuote(stock);
        total += shares * price;
    }
    return total;
}

</script>
</head>
<body>
</body>
</html>

Inheritance Concept

In JavaScript, an object has its own properties which is also inherited from their prototype object.

We will take an example to understand the concept of inheritance of properties by an object in JavaScript.

Example:

<html>
<head>
<title>JavaScript</title>
<script type="text/javascript">

let o = {};
o.x = 1;

let p = Object.create(o);
p.y = 2;

let q = Object.create(p);
q.z = 3;

let f = q.toString();
q.x + q.y

</script>
</head>
<body>
</body>
</html>
  • Here, object o inherits methods from Object.prototype.
  • Then it possesses its own property x.
  • An object p inherits properties from o and Object.prototype.
  • Then p has its own property y.
  • An object q inherits from p, o, and the previous objects.
  • Then q has its own property z.
  • An object has property, i.e. toString, which is inherited from Object.prototype.
  • Then the value 3 is computed from the last expression q.x+q.y.

Property Access Errors

There are times when property access expressions do not return or set a value due to some errors which we will discuss in this section.

We will take an example to look into few expression that throws errors instead of returning or setting a value.

Example:

<html>
<head>
<title>JavaScript</title>
<script type="text/javascript">

book.subtitle
let len = book.subtitle.length;

</script>
</head>
<body>
</body>
</html>

In the above example, we can see that the property subtitle does not exist, and also in the next line the length of the unexisting subtitle property also doesn’t exist.

In order to resolve such errors, we can use two ways to debug the errors.

Example:

<html>
<head>
<title>JavaScript</title>
<script type="text/javascript">

let surname = undefined;
if(book) {
    if (book.author) {
        surname = book.author.surname;
    }
}
surname = book && book.author &&book.author.surname;

</script>
</head>
<body>
</body>
</html>

In the above example, we have rectified the error in two ways. One was by the verbose and explicit technique and the second was by using a concise and idiomatic alternative to get surname or null or undefined.

Deleting of Properties

In JavaScript, we use the delete operator to remove a property from an object. It is a property access expression. However, delete operator operates on the whole property and not only on the value of the property.

  • The delete operator deletes the own properties or non-inherited properties of the object. It does not delete the inherited properties of the object.
  • The delete expression evaluates to true if the delete is succeeded or had no effect.
  • The delete expression does not remove properties having a configurable attribute of false.

We will take an example to understand how we can use the delete operator in JavaScript.

Example:

<html>
<head>
<title>JavaScript</title>
<script type="text/javascript">

delete book.author;
delete book["main title"];

let o = {x: 1};
delete o.x
delete o.x
delete o.toString
delete 1

</script>
</head>
<body>
</body>
</html>
  • Here, in line 6, the object book has no author property.
  • In line 7, the object book has no “main title” either.
  • In line 9, the object o has its own property x and inherits property toString.
  • In line 10, delete operator deletes property x and returns true.
  • In line 11, delete operator does nothing but returns true anyway.
  • In line 12, delete operator does nothing as toString is not own property.
  • In line 13, this statement is invalid but delete returns true anyways.

Enumeration of Properties

The object properties can be obtained through iterating an object. The loop is iterated once for each enumerable property of an object assigning the name of the property to the loop variable.

Example:

<html>
<head>
<title>JavaScript</title>
<script type="text/javascript">

let o = {x: 1, y: 2, z: 3};
o.propertyIsEnumerable("toString")

for(let p in o){
    console.log(p);
}

</script>
</head>
<body>
</body>
</html>
  • Here, object o has three enumerable own properties.
  • We can see in the above example that for loop is iterated through the properties of object o.
  • And each time the name of the property, i.e. x, y, and z is displayed using console.log().

In the next section of the tutorial, we will discuss Error Handling in JavaScript and their different types such as syntax errors, runtime errors, logical errors in a JavaScript program with some good examples for in-depth understanding.