CodeBlanks Logo Icon CodeBlanks

Summary - Arrays

Combine push, slice and forEach to write a class list.

Class list app

In this summary we will combine the array methods you learned to write a class list. The target output: print all students first, then a part with the first two.

The flow is: declare an empty students array; add three students with push; take a copy of the first two with slice(0, 2). Then print each array with console.log. This exercise combines accumulation with push and safe copying with slice.

Practice Write the class list

Declare an empty students array. Add three students with students.push("Alex"), students.push("Mia"), students.push("Noah"). Then declare firstTwo with students.slice(0, 2). Finally print firstTwo[0] with console.log. The output on a single line must be Alex.

Starter code

index.js
// Declare students array, add three students, slice the first two

Sample solution

index.js
const students = [];
students.push("Alex");
students.push("Mia");
students.push("Noah");
const firstTwo = students.slice(0, 2);
console.log(firstTwo[0]);

Expected output

Alex

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which method adds a new student to the class list?

index.js
students.???
  • .slice(name)
  • .push(name) Correct answer
  • .pop(name)
  • .length(name)

Explanation: push appends the student at the end.

2 Take the first two students

Question
const firstTwo = students____(0, 2);
Answer
const firstTwo = students.slice(0, 2);

Explanation: .slice(0, 2) gives a copy of the first two students.

3 Match each method to its job

Term Meaning
push Appends at end
slice Takes a copy part
[0] First element
length Element count

All lessons in Beginner