Objects
Object Literal Syntax & Basic Creation
An object is a collection of properties. Each property has a key (a string) and a value. Property values can be any type: strings, numbers, arrays, booleans, even other objects. Here we create an object with properties first, then an empty object.
const student = {
name: "Sarah",
age: 24,
courses: ["Web Development", "JavaScript"],
isEnrolled: true
};
console.log(student);
const emptyBox = {};
Key Points:
- Objects store related data together using properties
- Each property is a
key: valuepair - Property keys are always strings. Property values can be any type: string, number, array, boolean, object, etc.
- Use curly braces
{}to create an object
Accessing Properties: Dot vs Brackets
You can read object properties with dot notation or bracket notation. Most of the time dot notation is
simplest, but brackets are required for keys with spaces/special characters and for dynamic access using
a variable.
In this example, we create an object car with four properties. Then we get the value of
properties brand and model using dot notation.
Then we get the value of properties year and fuel type using bracket notation.
The last property access (car.owner) will return undefined because the
property doesn't exist.
const car = {
brand: "Toyota",
model: "Camry",
year: 2022,
"fuel type": "hybrid"
};
const carBrand = car.brand;
console.log(carBrand);
console.log(car.model);
console.log(car["year"]);
console.log(car["fuel type"]);
const propertyName = "model";
console.log(car[propertyName]);
console.log(car.owner);
Key Points:
- Dot notation (
obj.property) is simpler and used most often - Bracket notation (
obj["property"]) is required when property names have spaces or special characters (for example:"fuel type","user-name","@id") - Bracket notation allows you to use variables to access properties dynamically
- Both notations do the same thing - they retrieve the value stored at that property
- If you try to access a property that doesn't exist, you get
undefined(not an error)
Changing Objects: Adding, Modifying, and Deleting Properties
You can change an object after you create it: add new
properties, modify existing ones, or delete properties.
It's called mutability.
In this example, we create an object person with two properties: firstName and
age.
We then show how to add new properties, modify existing ones, and delete properties.
const person = {
firstName: "John",
age: 30
};
console.log(person);
person.lastName = "Doe";
person.city = "New York";
console.log(person);
person.age = 31;
console.log(person.age);
delete person.city;
console.log(person);
person["email"] = "john@example.com";
person["age"] = 32;
console.log(person);
Key Points:
- Assigning to a new key adds a new property:
person.lastName = "Doe" - Assigning to an existing key overwrites its value:
person.age = 31 delete person.cityremoves a property with key"city"from object- You can add, modify and delete properties with dot notation or bracket notation
- If a property is missing, reading it gives
undefined
Iterating Over Object Properties: for...in
Sometimes you want to look at every property in an object. With for...in, JavaScript gives
you one key at a time, and you can use that key to read the value.
const product = {
name: "Laptop",
price: 999,
inStock: true
};
for (const propertyKey in product) {
const propertyValue = product[propertyKey];
console.log("Key " + propertyKey + " has value " + propertyValue);
}
Key Points:
for...initerates over an object's property keys- When the key is in a variable, use brackets to read the value:
product[propertyKey]
Iterating Over Object Properties: Object.keys() + for...of
Another way is to turn the object's keys into an array with Object.keys(), then use
for...of to loop through that array and log both key and value.
const student = {
name: "Ava",
grade: "A"
};
const keys = Object.keys(student);
for (const key of keys) {
const value = student[key];
console.log(`${key}: ${value}`);
}
Key Points:
Object.keys(obj)creates an array of keysfor...ofiterates over arrays (like the keys array)- To get the value, use
obj[key]because key is a variable
Reading Object Properties with Destructuring
It's common to read value of object property and assign it to variable with the same name.
Destructuring is a feature that allows you to read values from objects and assign them to variables.
const user = { name: "Mina", age: 19, isStudent: true, score: 90 };
const { name } = user;
const { age: userAge } = user;
const { score, isStudent } = user;
console.log(`${name} is ${userAge} years old and ${isStudent ? "is" : "is not"} a student.`);
Key Points:
- Destructuring allow you to read one or more properties from an object and assign them to variables
const { name } = user;is shorthand forconst name = user.name;key: variableNamelets you read a property and assign it to a variable with a different name- Destructuring creates variables; it does not change the original object