Store several values in arrays, describe entities with objects, then learn how to read and modify them.
Open this lesson in KodokonSo far, each variable held a single value. An array is an ordered list of values, written between square brackets [ ], with the values separated by commas. Each value sits at a numbered position called an index. Careful: numbering starts at 0. The first element is therefore at index 0, the second at index 1, and so on. The length property gives the number of elements.
const fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]); // Prints: apple
console.log(fruits[2]); // Prints: cherry
console.log(fruits.length); // Prints: 3An array is easy to modify. The push(...) method adds an element at the end; a method is a function attached to a value, which you call with a dot. And the notation fruits[0] = ... replaces the element at the given index.
const fruits = ["apple", "banana"];
fruits.push("cherry"); // Adds at the end
fruits[0] = "pear"; // Replaces the first one
console.log(fruits);
// Prints: ["pear", "banana", "cherry"]An object groups several related pieces of information as key: value pairs, between curly braces { }. The key is a name, like the label of a field, and the value is the associated data. It is perfect for describing an everyday entity: a person, a product, a movie... You read or modify a property with a dot, for example user.name, and you can add a new property at any time.
const user = {
name: "Léa",
age: 28
};
console.log(user.name); // Prints: Léa
user.age = 29; // Modifies the property
user.city = "Lyon"; // Adds a property
console.log(user.age); // Prints: 29
console.log(user.city); // Prints: Lyonfruits?name property of the user object?