Author: M Abo Bakar Aslam
Objects
In JavaScript, an object is a fundamental data type and a complex, composite value that represents a collection of properties and methods. Objects are one of the core building blocks of the language and play a central role in JavaScript, as it is an object-oriented programming (OOP) language.
1. Object Definition
JavaScript objects are defined using curly braces {}. Properties are written as property-name: property-value pairs, separated by commas.
Example Code 1:
This example demonstrates defining an object with multiple properties such as firstName, lastName, age, and eyeColor. It also shows accessing properties using dot notation.
const person = {
firstName : "John",
lastName : "Doe",
age : 50,
eyeColor : "blue"
};
console.log("person age: ", person.age)
console.log("person first name: ", person.firstName)Example Code 2:
This example shows that an object can also be defined in a single line while maintaining the same structure and behavior.
const person = {firstName : "John", lastName : "Doe", age : 50, eyeColor : "blue" };
console.log("person age: ", person.age)
console.log("person first name: ", person.firstName) = ["Saab", "Volvo", "BMW"]
console.log(cars[i])Example Code 3:
This example demonstrates accessing object properties using square brackets and string keys instead of dot notation.
const person = {
firstName : "John",
lastName : "Doe",
age : 50,
eyeColor : "blue"
};
console.log("person age: ", person["age"])
console.log("person first name: ", person["firstName"])
Object Iteration2. Object Iteration
Object iteration refers to traversing and accessing properties of an object. It allows performing operations such as reading, modifying, or processing object data dynamically.
Common methods for iterating objects include:
for...inloopObject.keys(),Object.values(),Object.entries()forEach()
2.1. Using for...in Loop
The for...in loop iterates over enumerable properties of an object. Each iteration provides the property name (key), which can be used to access its value.
Example Code 4:
This example demonstrates iterating through an object and displaying only property names.
const person = {fname:"John", lname:"Doe", age:25}
//object iterating
for (let x in person) {
console.log(x)
}Example Code 5:
This example shows how to display both property names and their corresponding values using bracket notation.
const person = { firstName: "John", lastName: "Doe", age: 30 };
//object iterating
for (const key in person) { //let or const can use here
console.log(key + ": " + person[key]); //person.key cannot be used
}2.2. Object.keys(), Object.values(), Object.entries()
These built-in methods return arrays:
Object.keys()→ returns property namesObject.values()→ returns property valuesObject.entries()→ returns key-value pairs
These arrays can then be iterated using loops.
Example Code 6:
This example demonstrates extracting keys, values, and entries from an object and iterating through them.
Note:
- These methods include only enumerable properties
- To access all properties (including non-enumerable), use
Object.getOwnPropertyNames()
const person = { firstName: "John", lastName: "Doe", age: 30 };
//using differnt built-in functions to get object's contents
const keys = Object.keys(person); //keys is saved as array
const values = Object.values(person);//values is saved as array
const entries = Object.entries(person);//entries is saved as array
//iterate through each element of keys and access respective value using key
//here, we just used "keys" array
for (const key of keys) {
console.log(key + ": " + person[key]);
}
//displaying complete object in 2D array formate
for (const entry of entries) {
console.log(entry);
}2.3. Using forEach
You can convert object properties into arrays and iterate using the forEach() method.
Example Code 7:
This example demonstrates iterating through object keys using forEach() and accessing their corresponding values.
const person = { firstName: "John", lastName: "Doe", age: 30 }
//getting all properties-name and save into an array "keys"
const keys = Object.keys(person)
keys.forEach(key => {
console.log(key + ": " + person[key])
})3. Enumerable and Non-Enumerable Properties
Enumerable Properties
- Included by default in most objects
- Accessible via
for...inloop - Included in
Object.keys(),Object.values(), andObject.entries()
Non-Enumerable Properties
- Not included in iteration methods by default
- Often part of built-in or prototype properties
- Require special methods to access
Example Code 8:
This example demonstrates defining a non-enumerable property and shows how it behaves differently during iteration. It also highlights the use of Object.getOwnPropertyNames() to retrieve all properties.
const person = {
firstName: "John",
lastName: "Doe"
}
// Adding a non-enumerable property
Object.defineProperty(person, "age", {
value: 30,
enumerable: false
})
// Using for...in loop
for (const key in person) {
console.log(key + ": " + person[key])
}
// Using Object.keys()
const keys = Object.keys(person)
console.log(keys)
//getting non-enumerable property along with enumrable
const allProperties = Object.getOwnPropertyNames(person)
//displaying now properties and their values
for (const key of allProperties) {
console.log(key + ": " + person[key]);
}4. Object Copy and Merge
Objects can be copied or merged using the spread operator (...).
Example Code 9:
This example demonstrates merging two objects into a new object and creating a copy of an existing object.
// Create two objects
const person1 = { firstName: "John", lastName: "Doe" }
const person2 = { age: 30, job: "Engineer" }
// Copy and merge properties into a new object
const mergedPerson = { ...person1, ...person2 }
// only copy into cpObject
const cpObject = {...person2}
//displaying mergedPerson object
console.log(mergedPerson)
//displaying cpObject object
console.log(cpObject)5. Adding New Property to an Object
New properties can be added using:
- Dot notation
- Bracket notation
Example Code 10:
This example demonstrates adding new properties to an existing object and verifying them.
// Create two objects
const person = { firstName: "John", lastName: "Doe" }
//adding new property
person.age = 30 //dot notation
person["Qualification"] = "Engineer" //using bracket notation
//displaying object's properties to confirm
let objectProps = Object.entries(person)
for(prop of objectProps){
console.log(prop)
}6. Updating Property of an Object
Existing properties can be updated using:
- Dot notation
- Bracket notation
Example Code 11:
This example demonstrates updating values of existing object properties.
// Create two objects
const person = { firstName: "John", lastName: "Doe", "Qualification": "Engineer", "age": 25}
//updating the existing property
person.age = 30 //dot notation
person["Qualification"] = "Scientics" //using bracket notation
//displaying object's properties to confirm
let objectProps = Object.entries(person)
for(prop of objectProps){
console.log(prop)
}7. Deleting Property from an Object
The delete operator is used to remove properties from an object.
Example Code 12:
This example demonstrates deleting a property and verifying its removal.
Key Points:
- Deleting removes the property completely
- Accessing a deleted property returns
undefined - Non-configurable properties cannot be deleted
- Deleting does not affect array indexing
const person = {
firstName: "John",
lastName: "Doe",
age: 30
};
// Deleting the "age" property
delete person.age;
//displaying object to confirm
console.log(person)
//accessing again the deleted property
console.log(person.age)Example Code 13:
This example demonstrates deleting a non-existing property and introduces a best practice for checking property existence before deletion.
const person = {
firstName: "John",
lastName: "Doe",
age: 50
};
//deleting a non-existing property
delete person.fullname //no erro, no intimation
//best practice to delete
const propertyName = "age";
if (person.hasOwnProperty(propertyName)) {
delete person[propertyName];
} else {
console.log(`Property ${propertyName} does not exist.`);
}8. Object Destructuring
Object destructuring allows extracting values from objects and assigning them to variables in a concise way. It improves readability and reduces repetitive code.
Example Code 14:
This example demonstrates extracting multiple properties from an object into individual variables.
const person = {
firstName: "John",
lastName: "Doe",
age: 30
};
// Using object destructuring to extract values into variables
const { firstName, lastName, age } = person;
//displaying destructured properties
console.log(firstName); // "John"
console.log(lastName); // "Doe"
console.log(age); // 309. Nested Destructuring
Nested destructuring allows extracting values from nested objects.
Example Code 15:
This example demonstrates accessing deeply nested properties using destructuring.
Note:
Object manipulation and iteration are essential concepts in JavaScript. Mastering them enables efficient handling of structured and complex data in modern applications.
const company = {
name: "ABC Inc.",
address: {
street: "123 Main St",
city: "Anytown"
}
};
//destructuring from nested object
const { name, address: { city } } = company;
//displaying propery to confirm
console.log(city); // "Anytown"