JavaScript Basics: Make Web Pages Come Alive · Lesson 5 of 8

Lesson 5: Arrays and Objects

Store lists of values in arrays and described things in objects, and loop over both.

Lesson 5: Arrays and Objects

Arrays

An array is an ordered list in square brackets. Counting starts at 0.

const cities = ["Kathmandu", "Pokhara", "Biratnagar"];
console.log(cities[0]);
console.log(cities.length);
cities.push("Lalitpur");
console.log(cities);

Output:

Kathmandu
3
[ 'Kathmandu', 'Pokhara', 'Biratnagar', 'Lalitpur' ]

Loop over an array with for...of:

const marks = [72, 85, 64, 90];
let total = 0;
for (const m of marks) {
  total += m;
}
console.log(total / marks.length);

Output:

77.75

Handy array methods

map makes a new array by changing each item. filter keeps only items that pass a test. The small arrow functions x => ... are explained in the next lesson.

const marks = [72, 85, 64, 90, 38];
console.log(marks.map(m => m + 5));
console.log(marks.filter(m => m >= 60));

Output:

[ 77, 90, 69, 95, 43 ]
[ 72, 85, 64, 90 ]

Objects

An object stores named values (properties) in curly brackets. Use it for one thing described by labels.

const student = { name: "Anita", age: 17, city: "Butwal" };
console.log(student.name);
student.age = 18;
student.grade = "A";
console.log(student);

Output:

Anita
{ name: 'Anita', age: 18, city: 'Butwal', grade: 'A' }

Real programs often use an array of objects:

const students = [
  { name: "Sita", marks: 72 },
  { name: "Ram", marks: 85 },
];
for (const s of students) {
  console.log(`${s.name}: ${s.marks}`);
}

Output:

Sita: 72
Ram: 85

Try it yourself

  1. Make an array of five subjects and print them one per line.
  2. Use filter to keep marks of 40 or more.
  3. Create an object for a book and print its title and author.

Next lesson: functions.

Finished this lesson?Log in to save your progress and pick up where you left off.
Next lesson →

Comments

Loading comments…

MeroSir Team
A free MeroSir course. Run the examples yourself and try the exercises: you learn programming by doing. Spotted a mistake? Use the Report button above the lesson.
Lesson 5: Arrays and Objects | MeroSir