JAVASCRIPT
JavaScript Object: Syntax, Usage, and Examples
The JavaScript object is one of the most fundamental elements in the language. Objects allow you to store collections of key-value pairs and represent real-world entities in a flexible and dynamic way. From simple data containers to complex nested structures, the object JavaScript model is essential to understanding how JavaScript operates.
What Is a JavaScript Object?
A JavaScript object is a non-primitive data type used to store related data and functionalities. Each item in an object is stored as a key-value pair, making it ideal for representing structured data.
Learn JavaScript on Mimo
Basic Syntax
JSX
const person = {
name: "Alice",
age: 30,
isStudent: false
};
In this example, person is an object with three properties: name, age, and isStudent.
Creating Objects in JavaScript
There are multiple ways to create an object in JavaScript:
1. Object Literal
JSX
const car = {
brand: "Toyota",
model: "Camry"
};
This is the most common and concise way to define an object.
2. Using the Object Constructor
JSX
const car = new Object();
car.brand = "Toyota";
car.model = "Camry";
This method is more verbose and used less frequently.
3. Using a Function
JSX
function Person(name, age) {
this.name = name;
this.age = age;
}
const user = new Person("Bob", 25);
This technique is useful when creating multiple instances with the same structure.
Accessing and Modifying Object Properties
Properties can be accessed using dot or bracket notation.
JSX
console.log(person.name); // "Alice"
console.log(person["age"]); // 30
person.age = 31;
person["isStudent"] = true;
You can also dynamically assign keys using variables:
JSX
const key = "name";
console.log(person[key]); // "Alice"
Nested JavaScript Objects
Objects can contain other objects:
JSX
const user = {
name: "Sam",
contact: {
email: "sam@example.com",
phone: "123-456-7890"
}
};
console.log(user.contact.email); // "sam@example.com"
This structure supports complex data modeling.
Checking if Object Is Empty JavaScript
A common task is determining whether an object contains any keys.
Using Object.keys()
JSX
const obj = {};
const isEmpty = Object.keys(obj).length === 0;
console.log(isEmpty); // true
This is a reliable way to check if object is empty in JavaScript.
JavaScript Objects and Arrays
While both are objects under the hood, arrays are designed for ordered collections, whereas plain objects are best for key-value storage.
JSX
const arr = [1, 2, 3]; // Array
const obj = { a: 1, b: 2 }; // Object
Understanding this difference is important when deciding how to structure your data.
Object Methods
You can add functions (methods) to objects:
JSX
const user = {
name: "Jill",
greet() {
return `Hello, my name is ${this.name}`;
}
};
console.log(user.greet()); // "Hello, my name is Jill"
These methods can also access and manipulate internal properties using this.
Iterating Over Object Properties
There are several ways to loop through an object’s keys and values:
for...in Loop
JSX
for (let key in user) {
console.log(`${key}: ${user[key]}`);
}
Object.entries()
JSX
Object.entries(user).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});
Removing Keys from JavaScript Objects
If you want to delete a property, use the delete operator.
JSX
const book = {
title: "1984",
author: "George Orwell"
};
delete book.author;
console.log(book); // { title: "1984" }
This is the standard way to remove keys from a JavaScript object.
Converting JavaScript Object to String
You can convert an object into a string for logging, storage, or transmission using JSON.stringify().
JSX
const data = { name: "John", age: 40 };
const stringified = JSON.stringify(data);
console.log(stringified); // '{"name":"John","age":40}'
This technique is especially useful when sending objects over a network or saving them to local storage.
Document Object in JavaScript
The document object is a built-in object in browsers that represents the webpage. It’s part of the Document Object Model (DOM) and allows interaction with HTML content.
JSX
console.log(document.title); // Outputs the title of the page
You can use document to create elements, change text, and respond to user actions. It’s an example of a JavaScript object that provides rich functionality tied to the browser environment.
JavaScript Objects and Object-Oriented Programming
JavaScript supports object-oriented programming (OOP) even though it’s prototype-based. You can create classes and instances just like in traditional OOP languages.
JSX
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound.`;
}
}
const dog = new Animal("Rex");
console.log(dog.speak()); // "Rex makes a sound."
This answers the question "is JavaScript object oriented?" — Yes, it supports OOP principles using classes and prototypes.
Object Destructuring
ES6 introduced destructuring syntax, allowing you to unpack properties from objects directly.
JSX
const { name, age } = person;
console.log(name, age); // "Alice", 30
It simplifies working with objects and improves code readability.
Object Spread and Rest Operators
You can use spread (...) to copy or merge objects and rest to extract remaining properties.
JSX
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 }; // Merge with spread
console.log(obj2); // { a: 1, b: 2, c: 3 }
const { a, ...rest } = obj2;
console.log(rest); // { b: 2, c: 3 }
These modern JavaScript features make working with objects more powerful and expressive.
Sealing and Freezing Objects
You can control how mutable an object is using Object.freeze() and Object.seal():
JSX
const obj = { a: 1 };
Object.freeze(obj);
obj.a = 2;
console.log(obj.a); // Still 1
Use these to create immutable structures for safer code.
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot