Arrays and Objects
💻 JavaScriptStore collections of values in arrays and structured records in objects.
0 of 9 completed
A single variable holds one value. Arrays and objects let you hold many values in an organised way.
By the end of this lesson you can:
- Create and read arrays.
- Use common array methods.
- Create and update objects.
Arrays
An array is an ordered list. Indexes start at zero.
const fruits = ["mango", "orange", "pawpaw"];
console.log(fruits[0]); // mango
console.log(fruits.length); // 3
fruits.push("banana"); // add to the end
fruits.unshift("apple"); // add to the start
console.log(fruits);Array Methods
Methods such as map, filter and reduce transform arrays without writing manual loops.
const scores = [45, 72, 88, 61, 95];
const doubled = scores.map(score => score * 2);
const passed = scores.filter(score => score >= 70);
const total = scores.reduce((sum, score) => sum + score, 0);
console.log(doubled); // [90, 144, 176, 122, 190]
console.log(passed); // [72, 88, 95]
console.log(total); // 361Objects
An object stores named properties. Use dot notation or bracket notation to read and update them.
const student = {
name: "Amina",
age: 16,
subjects: ["Math", "English"],
isPrefect: false,
};
console.log(student.name); // Amina
student.age = 17;
student.subjects.push("Physics");
console.log(student.subjects); // ["Math", "English", "Physics"]Tip Use const for arrays and objects when you do not reassign the variable. You can still change their contents.
Practice
- Create an array of five subjects and print each one.
- Filter an array of scores to keep only the passing ones.
- Create an object describing yourself with at least four properties.
Hands-on exercise
Given the array [12, 5, 18, 7, 21, 3], write JavaScript that:
1. Keeps only numbers greater than 10.
2. Returns their total.
Print the result.
Recap
Arrays hold ordered lists and objects hold named properties. map, filter and reduce turn arrays into answers.
Example
const fruits = ["mango", "orange", "pawpaw"];
console.log(fruits[0]); // mango
console.log(fruits.length); // 3
fruits.push("banana"); // add to the end
fruits.unshift("apple"); // add to the start
console.log(fruits);
Exercises
Exercise 1. Filter and total
Medium
Given the array [12, 5, 18, 7, 21, 3], write JavaScript that:
1. Keeps only numbers greater than 10.
2. Returns their total.
Print the result.
1. Keeps only numbers greater than 10.
2. Returns their total.
Print the result.
JavaScript
exercise-1.js
Output
Expected Output
51