JS Objects

JavaScript Objects: A Beginner's Guide

An object is one of the most important concepts in JavaScript. It is a dynamic data structure that allows you to store related data as key-value pairs. You can think of an object like a real-world object—for example, a car has properties like color, model, and weight.


1. Creating JavaScript Objects

There are two primary ways to create an object in JavaScript.

Method 1: Using Object Literal (Recommended)

The object literal syntax is the most common and simple way to create objects. It allows you to define and initialize an object using curly braces {}, setting properties as key-value pairs separated by commas.

Object Literal Example

let obj = {
    name: "Akash",
    age: 23,
    job: "Developer"
};
console.log(obj);

Method 2: Using the new Object() Constructor

This method uses JavaScript's built-in Object constructor to create an empty object first, and then properties are added one by one.

Object Constructor Example

let obj = new Object();
obj.name = "Akash";
obj.age = 23;
obj.job = "Developer";

console.log(obj);


2. Basic Operations on JavaScript Objects

Let's look at the common actions you will perform on objects.

1. Accessing Object Properties

You can access an object’s properties using either dot notation (most common) or bracket notation (useful for dynamic keys).

Accessing Properties

let obj = { name: "Akash", age: 23 };

// Using Dot Notation console.log(obj.name); // Outputs: Akash

// Using Bracket Notation (quotes are required) console.log(obj["age"]); // Outputs: 23

2. Modifying Object Properties

Properties in an existing object can be easily updated by reassigning their values.

Modifying Properties

let obj = { name: "Akash", age: 22 };
obj.age = 23; // Updating the age

console.log(obj.age); // Outputs: 23

3. Adding New Properties

You can dynamically add completely new properties to an object at any time using dot or bracket notation.

Adding Properties

let obj = { model: "Tesla" };
obj.color = "Red"; // Dynamically added

console.log(obj); // { model: 'Tesla', color: 'Red' }

4. Removing Properties

The delete operator is used to completely remove a property from an object.

Removing Properties

let obj = { model: "Tesla", color: "Red" };
delete obj.color;

console.log(obj); // { model: 'Tesla' }

5. Checking if a Property Exists

You can check if a specific key exists inside an object using the in operator or the hasOwnProperty() method.

Checking Property Existence

let obj = { model: "Tesla" };

console.log("color" in obj); // false console.log(obj.hasOwnProperty("model")); // true

6. Iterating Through Object Properties

To loop through all the keys in an object, use the for...in loop.

Iterating Objects

let obj = { name: "Akash", age: 23 };

for (let key in obj) { console.log(key + ": " + obj[key]); }

7. Merging Objects

You can combine multiple objects together using Object.assign() or the modern spread syntax (...).

Merging Objects

let obj1 = { name: "Akash" };
let obj2 = { age: 23 };

let obj3 = { ...obj1, ...obj2 }; console.log(obj3); // { name: 'Akash', age: 23 }

8. Finding Object Length

Unlike arrays, objects do not have a built-in .length property. To find how many items are in an object, you first get its keys as an array using Object.keys(), and then find the length of that array.

Object Length

let obj = { name: "Akash", age: 23 };
console.log(Object.keys(obj).length); // 2

3. Recognizing a JavaScript Object Safely

To verify if a value is actually an object, use typeof and ensure it's not null (since in JavaScript, typeof null ironically returns "object").

Checking Object Type

let obj = { name: "Akash" };

// Verify it's an object AND it is not null console.log(typeof obj === "object" && obj !== null); // true


4. Best Practices and Common Mistakes

The literal {} vs new Object()

As we saw earlier, you can create objects in two ways. But why do developers prefer {}?

Feature {} (Object Literal) new Object() (Object Constructor)
Ease of Use More concise and readable. Less commonly used.
Performance Faster and more efficient (skips overhead). Slightly slower due to the constructor call.
Prototypal Inheritance Directly inherits from Object.prototype. Same, but adds an extra layer of abstraction.
Customization Literal syntax is sufficient for most use cases. Useful only in rare scenarios.
Reliability Fewer Errors. Using new Object() may unintentionally override the constructor if the environment changes.

Reason to use {}: It provides simpler syntax, better performance, and fewer errors!

Map vs Object

Another important concept is the difference between a standard Object and a Map structure:

Map Object
Stores key-value pairs and allows keys of any type (including objects). Stores key-value pairs but keys are always converted to strings or symbols.
Maintains the exact order of insertion. Does not guarantee key order.
Has a built-in size property to get the number of entries. No built-in property for size; must be calculated manually.
Iteration is easy using for...of or map.forEach(). Iteration requires for...in or Object.keys().
Better performance for frequent additions and removals of key-value pairs. May be slower for frequent additions/removals of properties.

Exercise

?

Which of the following is the recommended and most efficient way to create a new object in JavaScript?