Objects
What is an object?
Section titled “What is an object?”An object is a structure that allows storing data in the form of key/value pairs.
Each key is a string, and each value can be of any type (string, number, array, another object…).
Example in English:
- An object is like a descriptive sheet with fields.
Creating an object
Section titled “Creating an object”let person = { name: "Alice", age: 25, active: true};
console.log(person.name); // Aliceconsole.log(person["age"]); // 25
Dot notation vs Bracket notation
Section titled “Dot notation vs Bracket notation”- Dot notation (
person.name
) → more readable, but limited to valid identifier keys. - Bracket notation (
person["full name"]
) → useful if the key contains spaces or is stored in a variable.
Modifying an object
Section titled “Modifying an object”You can add or modify a property at any time:
let car = { brand: "Tesla", model: "Model 3" };car.color = "red";
console.log(car);
Iterating over an object
Section titled “Iterating over an object”The for...in
loop allows iterating over all the keys of an object.
let user = { name: "Bob", age: 30 };
for (let key in user) { console.log(key, ":", user[key]);}
Other useful methods
Section titled “Other useful methods”Object.keys(obj)
→ returns all the keys as an array.Object.values(obj)
→ returns all the values.Object.entries(obj)
→ returns[key, value]
pairs.
Example:
let user = { name: "Bob", age: 30 };
console.log(Object.keys(user)); // ["name", "age"]console.log(Object.values(user)); // ["Bob", 30]console.log(Object.entries(user)); // [["name","Bob"], ["age",30]]
Nested objects
Section titled “Nested objects”Objects can contain other objects (hierarchical structure).
let person = { name: "Alice", address: { city: "Paris", zipCode: 75000 }};
console.log(person.address.city); // Paris
JSON (JavaScript Object Notation) is a data format based on JS object syntax.
It is widely used for data exchange between a server and an application.
JSON.parse(string)
→ converts a JSON string into a JavaScript object.JSON.stringify(object)
→ converts an object into a JSON string.
let json = '{"name": "Alice", "age": 25}';let obj = JSON.parse(json);console.log(obj.name); // Alice
let string = JSON.stringify(obj);console.log(string); // {"name":"Alice","age":25}
Best practices
Section titled “Best practices”- Use dot notation if possible (
obj.prop
), otherwise use bracket notation (obj["prop"]
) when keys are not valid identifiers. - Think of
Object.keys()
,Object.values()
,Object.entries()
to easily manipulate objects. - Use JSON (
JSON.parse
/JSON.stringify
) to save or transfer data. - Organize your objects with nested objects if needed (e.g.,
address
insideperson
).