JavaScript Objects Guide: Keys, Values & Manipulation
Direct Answer & Key Concept
A JavaScript object is a standalone entity consisting of key-value properties. Keys are strings or symbols, and values can be any data type, including primitive types, arrays, functions, and nested objects.
// Object Methods in Practice
const userProfile = {
id: 101,
name: "Alex Mercer",
role: "Engineer"
};
// Iterating entries
Object.entries(userProfile).forEach(([key, value]) => {
console.log(`${key.toUpperCase()}: ${value}`);
});
// Safe cloning with structuredClone
const userCopy = structuredClone(userProfile);
userCopy.name = "Jordan";
console.log("Original:", userProfile.name); // "Alex Mercer"
console.log("Copy:", userCopy.name); // "Jordan"What is an object in JavaScript?
In JavaScript, an object is a non-primitive data structure that stores collections of keyed data values and complex entities. Objects are declared primarily using object literal syntax { ... }, where properties consist of key-value pairs separated by commas.
Property Access: Dot Notation vs Bracket Notation
JavaScript supports two ways to access and assign object properties:
- Dot Notation (
obj.key): Standard, concise syntax used when the property key is a known, valid identifier without spaces or special characters. - Bracket Notation (
obj["key"]): Required when property keys contain spaces, hyphens, start with numbers, or when the key is evaluated dynamically from a variable.
const user = {
name: "Alex",
"account-type": "premium"
};
console.log(user.name); // Dot notation
console.log(user["account-type"]); // Bracket notation required for hyphens
const dynamicKey = "name";
console.log(user[dynamicKey]); // "Alex"
Built-in Static Object Methods
Modern JavaScript provides powerful utilities on the global Object constructor for iterating and inspecting keys and values:
Object.keys(obj): Returns an array of the object's own enumerable string-keyed property names.Object.values(obj): Returns an array of the object's own enumerable property values.Object.entries(obj): Returns an array of key-value pairs:[['name', 'Alex'], ['role', 'Admin']].Object.assign(target, ...sources): Copies all enumerable own properties from source objects to a target object.Object.freeze(obj): Freezes an object, preventing new properties from being added, removed, or modified.
Shallow Copying vs Deep Copying Objects
- Shallow Copy (
{ ...obj }): Copies top-level properties. If a property references another object, both copies reference the same nested memory. - Deep Copy (
structuredClone(obj)): Recursively duplicates the entire object tree, ensuring full isolation between objects.