- Array() find
- -- operator
- -= operator
- ++ operator
- += operator
- Accessing and setting content
- AND operator
- Array concat() method
- Array indexOf()
- Array length
- Array pop()
- Array shift
- Arrays
- Booleans
- Braces
- Callback function
- Calling the function
- Class
- Closure
- Code block
- Comment
- Conditions
- Console
- Constructor
- Creating a p element
- Data types
- Date getTime()
- Destructuring
- Else
- Else if
- Enum
- Equals operator
- Error Handling
- ES6
- Event loop
- Events
- Extend
- Fetch API
- Filter
- For loop
- forEach()
- Function
- Function bind()
- Function name
- Greater than
- Head element
- Hoisting
- If statement
- includes()
- Infinity property
- Iterator
- JavaScript Array slice() method
- JSON
- Less than
- Local storage
- Map
- Methods
- Module
- Numbers
- Object
- Object.keys()
- Overriding methods
- Parameters
- Promises
- Random
- Reduce
- Regex
- Regular expressions
- Removing an element
- Replace
- Scope
- Session storage
- setTimeout() method
- Sleep() function
- Sort
- Splice
- String
- String concat()
- String indexOf()
- String slice() method
- Substring
- Switch statement
- Template literals
- Ternary operator
- throw Statement
- Title
- Type conversion
- void Operator
- While loop
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.
Basic Syntax
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
const car = {
brand: "Toyota",
model: "Camry"
};
This is the most common and concise way to define an object.
2. Using the Object Constructor
const car = new Object();
car.brand = "Toyota";
car.model = "Camry";
This method is more verbose and used less frequently.
3. Using a Function
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.
console.log(person.name); // "Alice"
console.log(person["age"]); // 30
person.age = 31;
person["isStudent"] = true;
You can also dynamically assign keys using variables:
const key = "name";
console.log(person[key]); // "Alice"
Nested JavaScript Objects
Objects can contain other objects:
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()
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.
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:
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
for (let key in user) {
console.log(`${key}: ${user[key]}`);
}
Object.entries()
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.
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()
.
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.
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.
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.
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.
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()
:
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.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.