Objects: Operations and Utility Methods
In JavaScript, almost everything is an object. An object is a collection of related data or functionality in the form of key-value pairs (properties and methods).
1. Creating Objects & Property Access
Objects are typically created using object literal syntax {}:
const car = {
make: "Toyota",
model: "Corolla",
year: 2022,
start: function() {
console.log("Engine started.");
}
};Accessing Properties:
You can read values using Dot Notation or Bracket Notation:
// Dot Notation
console.log(car.make); // "Toyota"
// Bracket Notation (Required when property keys contain spaces or are dynamic variables)
console.log(car["model"]); // "Corolla"
let key = "year";
console.log(car[key]); // 20222. Managing Properties (CRUD)
Properties in JavaScript objects can be added, updated, or deleted dynamically:
const user = { name: "Alice" };
// 1. Create / Update
user.age = 25; // Adds new property 'age'
user.name = "Bob"; // Updates existing property 'name'
// 2. Delete
delete user.age; // Removes property 'age'
console.log(user); // { name: "Bob" }3. Useful Object Methods
JavaScript provides a global Object constructor with utility methods to inspect and manipulate objects.
A. Extracting Keys, Values, and Entries
Object.keys(obj): Returns an array of an object's keys (property names).Object.values(obj): Returns an array of an object's values.Object.entries(obj): Returns an array of an object's[key, value]pairs.
const user = { name: "Alice", age: 25 };
console.log(Object.keys(user)); // ["name", "age"]
console.log(Object.values(user)); // ["Alice", 25]
console.log(Object.entries(user)); // [["name", "Alice"], ["age", 25]]B. Cloning and Merging: Object.assign()
Copies properties from source objects to a target object.
const defaultSettings = { theme: "light", showSidebar: true };
const userSettings = { theme: "dark" };
// Merge settings into a new object:
const settings = Object.assign({}, defaultSettings, userSettings);
console.log(settings); // { theme: "dark", showSidebar: true }C. Immutability: freeze() and seal()
Object.seal(obj): Prevents adding or deleting properties. Existing properties can still be updated.Object.freeze(obj): Makes an object completely read-only. Prevents adding, deleting, or editing properties.
const config = { apiEndpoint: "https://api.example.com" };
Object.freeze(config);
config.apiEndpoint = "https://hacked.com"; // Ignored in normal mode, throws Error in strict mode
console.log(config.apiEndpoint); // "https://api.example.com"In the next guide, we will cover array operations and modern functional array methods like map, filter, and reduce.
Published on Last updated: