Kodokon kodokon.com

Arrays and objects: creating, reading, modifying

Store several values in arrays, describe entities with objects, then learn how to read and modify them.

8 min · 3 questions

Open this lesson in Kodokon

So 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.

JAVASCRIPT
const fruits = ["apple", "banana", "cherry"];

console.log(fruits[0]);     // Prints: apple
console.log(fruits[2]);     // Prints: cherry
console.log(fruits.length); // Prints: 3
Creating an array and reading its elements

An 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.

JAVASCRIPT
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"]
Adding and replacing elements

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.

JAVASCRIPT
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: Lyon
Creating, reading and modifying an object

Knowledge check

Make sure you remember the key points of this lesson.

  1. How do you read the first element of an array named fruits?
    • fruits[1]
    • fruits[0]
    • fruits.first
  2. Which method adds an element at the end of an array?
    • push()
    • add()
    • append()
    • insert()
  3. How do you read the name property of the user object?
    • user.name
    • name.user
    • user->name