Lesson 41 of 296
Objects: the basics
What you will learn
- What an object is
- Keys and values
- Dot notation and bracket notation
- Adding, changing and deleting properties
- Nested objects and arrays of objects
- Methods
- Shorthand syntax
- Getting the keys and values of an object
On this page
What is an object?
An object groups related data together using names instead of index numbers. Each piece is a key-value pair, also called a property.
const user = {
name: "Sam",
age: 30,
isAdmin: false
};| Key | Value |
|---|---|
name | "Sam" |
age | 30 |
isAdmin | false |
Use an array for a list of similar things in order. Use an object to describe one thing with named details.
Reading values
Dot notation:
user.name "Sam"
user.age 30
user.email undefined (key does not exist)Bracket notation: the key as a string.
user["name"] "Sam"Bracket notation is needed when:
- the key is stored in a variable:
const field = "age";
user[field]; 30
user.field; undefined (looks for a key literally called "field")- the key has spaces or hyphens:
headers["content-type"].
Adding, changing and deleting
user.email = "sam@example.com"; adds a new property
user.age = 31; changes a value
delete user.isAdmin; removes a propertyLike arrays, a const object can still be changed inside. const only stops you replacing the whole object.
Checking whether a key exists
"email" in user true
user.email !== undefined true (but fails if the value really is undefined)
Object.hasOwn(user, "email") true (checks only the object itself)Nested objects
const order = {
id: 1042,
customer: {
name: "Sam",
address: {
city: "Leeds",
postcode: "LS1 4AP"
}
},
items: ["Kettle", "Toaster"]
};
order.customer.address.city "Leeds"
order.items[0] "Kettle"
order.items.length 2Arrays of objects
This is the most common data shape you will see from APIs:
const products = [
{ id: 1, name: "Kettle", pricePence: 2999 },
{ id: 2, name: "Toaster", pricePence: 3499 }
];
products[1].name "Toaster"Methods
A method is a function stored inside an object.
const calculator = {
add(a, b) {
return a + b;
},
subtract(a, b) {
return a - b;
}
};
calculator.add(2, 3); 5console.log is also a method: log is a function inside the console object.
Shorthand
If a variable has the same name as the key, write it once:
const name = "Sam";
const age = 30;
const user = { name, age }; same as { name: name, age: age }Keys, values and entries
const user = { name: "Sam", age: 30 };
Object.keys(user) ["name", "age"]
Object.values(user) ["Sam", 30]
Object.entries(user) [["name", "Sam"], ["age", 30]]These turn an object into arrays you can loop over (Lesson 42).
Objects are compared and copied by reference
const a = { x: 1 };
const b = a; b points to the same object
b.x = 99;
console.log(a.x); 99b = a does not make a copy. To copy:
const copy = { ...a };This is a shallow copy: nested objects inside are still shared. Part 5 explains shallow and deep copies.
JSON
JSON is a text format for sending data. It looks almost exactly like JavaScript objects, but keys must use double quotes and functions are not allowed.
const text = JSON.stringify(user); object to JSON text
const back = JSON.parse(text); JSON text to objectAPIs send and receive JSON all the time. Part 5 covers it in more detail.
Common mistakes
user.fieldwhen the key is in a variable. Useuser[field].- Reading deep properties when a middle level is missing:
order.customer.address.citythrows an error ifaddressisundefined. Optional chaining?.fixes this (Part 5). - Thinking
b = acopies an object. - Missing commas between properties.
How to say it in an interview
"An object stores key-value pairs. I use dot notation normally and bracket notation when the key is dynamic or not a valid identifier. Objects are passed and assigned by reference, so assigning one to another variable does not copy it; the spread operator makes a shallow copy. Object.keys, values and entries turn an object into arrays for looping, and JSON.stringify and JSON.parse convert to and from JSON text."
Key words
| Word | Meaning |
|---|---|
| Object | A collection of named values |
| Property | One key-value pair |
| Key | The name of a property |
| Dot notation | user.name |
| Bracket notation | user["name"] |
| Method | A function stored in an object |
| Nested | An object or array inside another |
| JSON | A text format for data, based on JavaScript object syntax |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.