Objects: properties, methods and copying
Course contents (16 lessons)
- Getting started
- What is JavaScript and where does it run?
- Variables with let and const
- Values and operators
- Data types: numbers, strings, booleans, null and undefined
- Operators: arithmetic, comparison and logical
- Strings and template literals
- Making decisions and repeating work
- Conditionals: if, else and switch
- Loops: for, while and for...of
- Functions
- Functions: declarations, parameters and return values
- Arrow functions and callbacks
- Arrays and objects
- Arrays: creating, reading and changing lists
- Array methods: map, filter, find and reduce
- Objects: properties, methods and copying
- Scope and the browser
- Scope and closures, gently
- The DOM: selecting and changing elements
- Events: reacting to clicks, input and forms
- Final project
- Project: build a to-do list in the browser
What an object is
An array is a list. An object is a set of named values. You use an object to describe one thing, such as a user, a product or a settings panel. Each name is called a key (or property name), and it points to a value.
const user = {
name: "Sara",
age: 28,
city: "Lahore",
isAdmin: false,
};
Keys are usually written without quotes. Values can be any type, including arrays and other objects.
Reading and changing properties
const user = {
name: "Sara",
age: 28,
city: "Lahore",
skills: ["HTML", "CSS"],
address: { street: "Main Road", zip: "54000" },
};
console.log(user.name); // dot notation
console.log(user["city"]); // bracket notation
console.log(user.address.zip); // nested
console.log(user.skills[0]); // array inside object
console.log(user.phone); // undefined, no such key
user.age = 29; // change
user.email = "sara@example.com"; // add
delete user.city; // remove
console.log(user);
Use dot notation most of the time. Use brackets when the key is stored in a variable or is not a valid name:
const field = "name";
console.log(user[field]); // "Sara"
As before, const only stops you from reassigning user. You can still change its properties.
Methods
A function stored in an object is called a method. Inside a method, this refers to the object it was called on.
const account = {
owner: "Ali",
balance: 1000,
deposit(amount) {
this.balance += amount;
return this.balance;
},
describe() {
return `${this.owner} has Rs. ${this.balance}`;
},
};
account.deposit(500);
console.log(account.describe()); // Ali has Rs. 1500
When you write account.deposit(500), this inside deposit is account. That is why this.balance finds the right number.
Shorthand and computed keys
When a variable name matches the key you want, you can write it once:
const name = "Omar";
const age = 31;
const person = { name, age };
console.log(person); // { name: 'Omar', age: 31 }
Looping over an object
const prices = { tea: 50, coffee: 120, juice: 90 };
console.log(Object.keys(prices)); // ["tea", "coffee", "juice"]
console.log(Object.values(prices)); // [50, 120, 90]
console.log(Object.entries(prices)); // [["tea", 50], ["coffee", 120], ["juice", 90]]
for (const [item, price] of Object.entries(prices)) {
console.log(`${item} costs ${price}`);
}
console.log("tea" in prices); // true
console.log(prices.hasOwnProperty("milk")); // false
Because Object.values gives an array, you can use reduce to total it, or map to change it.
References: the part that trips people up
Numbers and strings are copied when you assign them. Objects and arrays are not. A variable holding an object really holds a reference, which is like an address. Assigning it to another variable copies the address and not the object.
const a = { score: 10 };
const b = a; // same object, two names
b.score = 99;
console.log(a.score); // 99
console.log({} === {}); // false, two different objects
console.log(a === b); // true, the same object
This is why two objects with identical content are not equal, and why changing an object inside a function changes it for the caller too.
Copying objects
Use the spread syntax to make a shallow copy:
const original = { name: "Ali", address: { city: "Lahore" } };
const copy = { ...original, name: "Bilal" };
console.log(copy.name); // "Bilal"
console.log(original.name); // "Ali"
copy.address.city = "Karachi";
console.log(original.address.city); // "Karachi" !
Spread copies the top level only. The nested address is still shared. This is a shallow copy. For a full independent copy, use structuredClone:
const deep = structuredClone(original);
deep.address.city = "Multan";
console.log(original.address.city); // unchanged
JSON: objects as text
When you send data to a server or save it, you turn an object into a string and back:
const text = JSON.stringify({ name: "Sara", age: 28 });
console.log(text); // {"name":"Sara","age":28}
const back = JSON.parse(text);
console.log(back.name); // "Sara"
JSON looks like an object literal but is just text with stricter rules: keys must be in double quotes, and no functions are allowed. You will use this a lot with APIs and local storage.
Common mistakes
- Reading a missing property of undefined.
user.address.streetcrashes ifaddressis missing. Useuser.address?.street. - Assuming a copy when you only made a second reference. Use spread or
structuredClone. - Using an arrow function as a method.
thiswill not point to the object. - Comparing objects with ===. It compares references, not content.
- Forgetting quotes in JSON.
JSON.parse("{name: 'Ali'}")throws an error. JSON needs{"name": "Ali"}.
Try it yourself
- Create an object for a book with title, author, year and a method
describe()that returns a sentence. - Add a new property
pages, changeyear, and removeauthor. Print the object each time. - Make a shallow copy of an object with a nested array, push to the nested array in the copy, and watch what happens to the original.
- Turn an object into JSON text and parse it back. Check whether the result is
===to the original.
const user = {
name: "Sara",
age: 28,
city: "Lahore",
skills: ["HTML", "CSS"],
address: { street: "Main Road", zip: "54000" },
};
console.log(user.name); // dot notation
console.log(user["city"]); // bracket notation
console.log(user.address.zip); // nested
console.log(user.skills[0]); // array inside object
console.log(user.phone); // undefined, no such key
user.age = 29; // change
user.email = "sara@example.com"; // add
delete user.city; // remove
console.log(user);
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account