Object Basics
Learn how to create, access, and modify objects in JavaScript.
Object Basics
Arrays store ordered lists — items at index 0, 1, 2. But what if your data has named properties instead of positions? A user has a name, an age, a city — not a position 0, 1, 2.
That is what objects are for. An object is a collection of named values — called key-value pairs — stored together under one variable.
const user = {
name: "Ali",
age: 22,
city: "Lahore"
};Instead of three separate variables, everything about the user lives in one place. name, age, and city are the keys. "Ali", 22, "Lahore" are the values.
Creating an Object
Objects are created with curly braces {}. Each key-value pair is separated by a comma, and the key and value are separated by a colon.
const person = {
name: "Sara",
age: 25,
isStudent: true,
city: "Karachi"
};Keys are always strings under the hood — but you don't need to quote them unless the key has spaces or special characters:
const obj = {
normalKey: "works fine",
"key with spaces": "needs quotes",
"key-with-hyphens": "needs quotes too"
};Values can be any type — strings, numbers, booleans, arrays, other objects, even functions:
const user = {
name: "Ali",
age: 22,
scores: [88, 92, 76],
address: {
city: "Lahore",
country: "Pakistan"
},
greet: function() {
console.log("Hello!");
}
};Accessing Values
Dot Notation
The most common way — use a dot followed by the key name.
const user = { name: "Ali", age: 22, city: "Lahore" };
console.log(user.name); // Ali
console.log(user.age); // 22
console.log(user.city); // LahoreBracket Notation
Use square brackets with the key as a string. Useful when the key is dynamic or has special characters.
console.log(user["name"]); // Ali
console.log(user["age"]); // 22The real power of bracket notation — using a variable as the key:
const key = "name";
console.log(user[key]); // Ali — looks up whatever key holds// Practical use — dynamic property access
const fields = ["name", "age", "city"];
for (const field of fields) {
console.log(`${field}: ${user[field]}`);
}
// name: Ali
// age: 22
// city: LahoreYou cannot do this with dot notation — user.field would look for a key literally called "field", not the value of the variable.
Accessing Nested Values
Chain dot or bracket notation to reach nested properties:
const user = {
name: "Ali",
address: {
city: "Lahore",
country: "Pakistan"
}
};
console.log(user.address.city); // Lahore
console.log(user.address.country); // PakistanModifying Values
Assign a new value to an existing key the same way you would with a variable:
const user = { name: "Ali", age: 22 };
user.age = 23;
user.name = "Ali Hassan";
console.log(user); // { name: "Ali Hassan", age: 23 }Just like arrays, objects declared with const can have their properties changed. const only prevents reassigning the variable itself — user = {} would fail, but user.age = 23 is fine.
Adding and Deleting Properties
Adding
Simply assign to a key that does not exist yet:
const user = { name: "Ali" };
user.age = 22;
user.city = "Lahore";
console.log(user); // { name: "Ali", age: 22, city: "Lahore" }Deleting
Use the delete operator to remove a property:
const user = { name: "Ali", age: 22, city: "Lahore" };
delete user.city;
console.log(user); // { name: "Ali", age: 22 }Checking if a Property Exists
Accessing a key that does not exist returns undefined — but that can be ambiguous since the value might intentionally be undefined. Use in operator or hasOwnProperty() to check properly.
const user = { name: "Ali", age: 22 };
console.log("name" in user); // true
console.log("city" in user); // false
console.log(user.hasOwnProperty("name")); // true
console.log(user.hasOwnProperty("city")); // falseLooping Over an Object
Use for...in to loop over all keys, then access each value with bracket notation:
const user = { name: "Ali", age: 22, city: "Lahore" };
for (const key in user) {
console.log(`${key}: ${user[key]}`);
}
// name: Ali
// age: 22
// city: LahoreOr use the static Object methods to get arrays of keys, values, or both:
console.log(Object.keys(user));
// ["name", "age", "city"]
console.log(Object.values(user));
// ["Ali", 22, "Lahore"]
console.log(Object.entries(user));
// [["name", "Ali"], ["age", 22], ["city", "Lahore"]]Object.entries() is especially useful with for...of and destructuring:
for (const [key, value] of Object.entries(user)) {
console.log(`${key}: ${value}`);
}
// name: Ali
// age: 22
// city: LahoreShorthand Property Names
When a variable name matches the key name you want, you can use shorthand — just write the variable name once.
const name = "Ali";
const age = 22;
const city = "Lahore";
// Old way
const user = { name: name, age: age, city: city };
// Shorthand — much cleaner
const user = { name, age, city };
console.log(user); // { name: "Ali", age: 22, city: "Lahore" }You will see this everywhere in modern JavaScript — especially when building objects from existing variables.
Computed Property Names
You can use an expression as a key name by wrapping it in square brackets:
const field = "name";
const user = {
[field]: "Ali" // key becomes "name"
};
console.log(user.name); // AliReal use — building objects dynamically:
function createSetting(key, value) {
return { [key]: value };
}
console.log(createSetting("theme", "dark"));
// { theme: "dark" }
console.log(createSetting("language", "en"));
// { language: "en" }Objects Are Reference Types
Just like arrays, objects are reference types. Copying an object with = does not create a new object — both variables point to the same one.
const original = { name: "Ali", age: 22 };
const copy = original;
copy.name = "Sara";
console.log(original.name); // Sara — original changed too
console.log(copy.name); // SaraTo make a real shallow copy, use spread or Object.assign():
const original = { name: "Ali", age: 22 };
// Spread copy
const copy1 = { ...original };
// Object.assign copy
const copy2 = Object.assign({}, original);
copy1.name = "Sara";
console.log(original.name); // Ali — unchanged
console.log(copy1.name); // SaraBoth spread and Object.assign() create shallow copies. Nested objects are still shared by reference. For deeply nested objects you need a deep copy — covered when we reach the Advanced section.
A Real Example — User Profile
const user = {
username: "ali_dev",
email: "ali@example.com",
age: 22,
location: {
city: "Lahore",
country: "Pakistan"
},
skills: ["JavaScript", "React", "Node.js"],
isVerified: true
};
// Access nested data
console.log(`${user.username} from ${user.location.city}`);
// ali_dev from Lahore
// Loop over top level keys
for (const [key, value] of Object.entries(user)) {
if (typeof value !== "object") {
console.log(`${key}: ${value}`);
}
}
// username: ali_dev
// email: ali@example.com
// age: 22
// isVerified: true
// Update a property
user.age = 23;
// Add a new property
user.website = "ali.dev";
// Check if property exists
console.log("website" in user); // true
console.log("phone" in user); // falseSummary
- An object is a collection of key-value pairs stored under one variable
- Created with curly braces —
const obj = { key: value } - Access values with dot notation
obj.keyor bracket notationobj["key"] - Use bracket notation when the key is dynamic or stored in a variable
- Add properties by assigning to a new key —
obj.newKey = value - Remove properties with
delete obj.key - Check if a property exists with the
inoperator orhasOwnProperty() - Loop with
for...inorObject.keys(),Object.values(),Object.entries() - Use shorthand when variable name matches key name —
{ name, age } - Objects are reference types — use spread to make a real copy