Summary - Array basics
Build a queue app using push, pop, shift and unshift.
Arrays: summary
In this group you learned the basics of arrays. An array literal is created with []; you access elements by index.
push appends to the end, unshift prepends to the start. pop removes from the end, shift removes from the start. All mutate the array directly.
length gives the element count; the last element is at length - 1. Nested arrays hold grid data, and you access cells with two indices.
Exercise Add and remove elements from the cart array
Create an empty array named cart. First add two strings with a single push call. Then remove the first element with shift. Finally print cart.length with console.log.
Show example solution
Define an empty cart array, push two strings, shift one out, then print the length.
Example solution:
const cart = [];
cart.push("bread", "milk");
cart.shift();
console.log(cart.length);
Exercise Print a cell from the board array
Create a nested array named board with two rows. Each row must have at least two numbers. Then print board[0][1] with console.log.
Show example solution
Define a board array with two rows of two numbers, then print board[0][1].
Example solution:
const board = [[1, 2], [3, 4]];
console.log(board[0][1]);
Test yourself
-
After the code runs, what is the final state of the nums array?
const nums = [1, 2, 3]; nums.push(4); nums.shift();- [2, 3, 4]
- [1, 2, 3, 4]
- [1, 2, 3]
- [2, 3]
Show answer
[2, 3, 4] — Correct. push appends 4, shift removes 1; the result is [2, 3, 4].
-
Access the last element of the items array
const items = ["a", "b", "c", "d"]; const last = items[____]; console.log(last);Show answer
const items = ["a", "b", "c", "d"]; const last = items[items.length - 1]; console.log(last);