- Create an object and read, change, add and delete properties
- Destructure objects and arrays
- Copy and merge with
...and understand copying by reference - Handle missing values safely with
?.and??
A student card shows a name, an age, a city and hobbies. You could keep them in four separate variables, but they belong together — they all describe the same student. In JavaScript, all the data about one thing is kept together in an object.
Objects and properties
A collection of key: value pairs written in curly braces. Each pair is called a property; the value can be of any type — a number, a string, an array, another object or a function.
You access a property with a dot (student.name) or with square brackets (student['name']). Brackets are needed when the key's name is stored in a variable. To add a new property, just assign it a value; delete removes a property.
const student = {
name: 'Aysel',
age: 14,
city: 'Baku',
hobbies: ['chess', 'music'],
};
console.log(student.name);
console.log(student['city']);
console.log(student.hobbies[1]);
const key = 'age';
console.log(student[key]);
student.age = 15;
student.grade = 9;
delete student.city;
console.log(student);▸ Expected output
Aysel
Baku
music
14
{ name: 'Aysel', age: 15, hobbies: [ 'chess', 'music' ], grade: 9 }A property whose value is a function is called a method. Inside a method, the word this refers to the object itself. Object.keys, Object.values and Object.entries return an object's keys, values and pairs as arrays — handy for looping over them.
const counter = {
count: 0,
increase() {
this.count++;
return this.count;
},
};
counter.increase();
console.log(counter.increase());
const prices = { bread: 0.8, milk: 1.5, tea: 4 };
console.log(Object.keys(prices));
console.log(Object.values(prices));
for (const item of Object.keys(prices)) {
console.log(`${item}: ${prices[item]} AZN`);
}▸ Expected output
2 [ 'bread', 'milk', 'tea' ] [ 0.8, 1.5, 4 ] bread: 0.8 AZN milk: 1.5 AZN tea: 4 AZN
In real programs you most often work with an array of objects: a shop's products, the students of a class, orders. The array methods from the previous lesson are very useful here.
const products = [
{ name: 'Laptop', price: 1200 },
{ name: 'Mouse', price: 25 },
{ name: 'Desk', price: 300 },
];
const cheap = products
.filter((p) => p.price < 500)
.map((p) => p.name);
const total = products.reduce((sum, p) => sum + p.price, 0);
console.log(cheap);
console.log('Total:', total);
console.log(products.find((p) => p.price > 1000));▸ Expected output
[ 'Mouse', 'Desk' ]
Total: 1525
{ name: 'Laptop', price: 1200 }Destructuring
Destructuring lets you unpack several values from an object or an array into separate variables in one line. With objects, variables are picked by key name; with arrays, by position. You can also rename (name: firstName) and set default values (country = 'Azerbaijan').
const user = { name: 'Murad', age: 16, city: 'Ganja' };
const { name, age } = user;
console.log(name, age);
const { name: firstName, country = 'Azerbaijan' } = user;
console.log(firstName, country);
const [gold, silver] = ['Leyla', 'Elvin', 'Aysel'];
console.log(gold, silver);
function printCard({ name, city }) {
console.log(`${name} lives in ${city}`);
}
printCard(user);▸ Expected output
Murad 16 Murad Azerbaijan Leyla Elvin Murad lives in Ganja
Spread and rest: three dots
The ... operator “spreads out” an array or object — this is called spread. With it you can make copies, join arrays and create a new object with some properties changed. If the same property appears twice, the last one wins. In destructuring, ... collects “everything else” — this is called rest.
const morning = ['tea', 'bread'];
const evening = ['soup', 'salad'];
const menu = [...morning, 'lunch', ...evening];
console.log(menu);
console.log(Math.max(...[4, 17, 9]));
const defaults = { theme: 'light', lang: 'az', fontSize: 16 };
const settings = { ...defaults, theme: 'dark' };
console.log(settings);
const { lang, ...others } = settings;
console.log(lang, others);▸ Expected output
[ 'tea', 'bread', 'lunch', 'soup', 'salad' ]
17
{ theme: 'dark', lang: 'az', fontSize: 16 }
az { theme: 'dark', fontSize: 16 }const original = { score: 10 };
const sameObject = original;
const copy = { ...original };
sameObject.score = 99;
console.log(original.score);
console.log(copy.score);▸ Expected output
99 10
Missing values: ?. and ??
Data from a server may lack some properties. Trying to read a property of null causes an error. Optional chaining ?. prevents this: if the left side is null or undefined, it simply returns undefined. The ?? operator gives a fallback value on the right when the left side is null or undefined.
const account = { login: 'elvin', profile: null };
console.log(account.profile?.avatar);
console.log(account.profile?.avatar ?? 'default.png');
const volume = 0;
console.log(volume || 50);
console.log(volume ?? 50);▸ Expected output
undefined default.png 50 0
|| replaces any falsy value (including 0), while ?? replaces only null and undefined.1) Use destructuring to take name and city from student and print them on one line. 2) Use spread to create a copy of the object with age set to 16, and print the copy. 3) Print student.age to check that the original has not changed.
const student = { name: 'Murad', age: 15, city: 'Baku' };
// 1) destructure name and city and print them
// 2) copy the object with spread, set age to 16, print the copy
// 3) print student.age▸ Expected output
Murad Baku
{ name: 'Murad', age: 16, city: 'Baku' }
15Key points
- An object is made of
key: valuepairs; properties are accessed with.or[ ]. - A property that is a function is a method; inside it
thisis the object itself. - Destructuring
const { a, b } = objandconst [x, y] = arrunpacks values into variables. ...as spread copies and merges; as rest it collects what is left.b = ais not a copy of an object but a reference to the same object.?.prevents errors on missing properties,??provides a fallback value.
Check yourself
10 questions. Every correct answer earns XP.
field, how do you read the property?