Skip to content

Objects

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.

let person = {
name: "Alice",
age: 25,
active: true
};
console.log(person.name); // Alice
console.log(person["age"]); // 25
  • 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.

You can add or modify a property at any time:

let car = { brand: "Tesla", model: "Model 3" };
car.color = "red";
console.log(car);

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]);
}
  • 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]]

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}

  • 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 inside person).