Skip to main content

Chapter 6 - Lists (JavaScript)

Here's a JavaScript-flavoured version of the same concepts, with small JS examples for each idea.


Array basics

JavaScript uses arrays (equivalent to Python lists), written with square brackets.

Example:

const spam = ["cat", "bat", "rat", "elephant"];
console.log(spam); // ['cat', 'bat', 'rat', 'elephant']
const empty = [];

Indexes and nested arrays

Indexes start at 0. You can index into nested arrays with multiple brackets.

Example:

const spam = ["cat", "bat", "rat", "elephant"];
console.log(spam[0]); // 'cat'
console.log(spam[3]); // 'elephant'

const grid = [["cat", "bat"], [10, 20, 30]];
console.log(grid[0]); // ['cat', 'bat']
console.log(grid[0][1]); // 'bat'
console.log(grid[1][2]); // 30

Using an index too large returns undefined (no error thrown).


Negative indexes with .at()

JavaScript doesn't support negative indexes directly, but .at() does.

Example:

const spam = ["cat", "bat", "rat", "elephant"];
console.log(spam.at(-1)); // 'elephant'
console.log(spam.at(-3)); // 'bat'

Slices with .slice()

.slice(start, end) returns a new array from start up to but not including end.

Example:

const spam = ["cat", "bat", "rat", "elephant"];
console.log(spam.slice(1, 3)); // ['bat', 'rat']
console.log(spam.slice(0, 2)); // ['cat', 'bat']
console.log(spam.slice(1)); // ['bat', 'rat', 'elephant']
console.log(spam.slice()); // full copy

.length (equivalent of len())

.length returns how many items are in the array.

Example:

const spam = ["cat", "dog", "moose"];
console.log(spam.length); // 3

Updating items

You can assign to an index to change that item's value.

Example:

const spam = ["cat", "bat", "rat", "elephant"];
spam[1] = "aardvark";
spam[3] = 12345;
console.log(spam); // ['cat', 'aardvark', 'rat', 12345]

Array concatenation and replication

.concat() or spread ... joins arrays. Array(n).fill(x) repeats a value.

Example:

console.log([1, 2, 3].concat(["A", "B"]));   // [1, 2, 3, 'A', 'B']
console.log(Array(3).fill(["X", "Y"]).flat()); // ['X', 'Y', 'X', 'Y', 'X', 'Y']

splice to remove by index

.splice(index, count) removes items at a given index (modifies in place), similar to Python's del.

Example:

const spam = ["cat", "bat", "rat", "elephant"];
spam.splice(2, 1);
console.log(spam); // ['cat', 'bat', 'elephant']

Using arrays instead of many variables

Arrays avoid a pile of nearly identical variables and scale with any number of items.

Example (dynamic cat list):

const catNames = [];
while (true) {
console.log("Enter the name of cat " + (catNames.length + 1) + " (or enter nothing to stop):");
const name = prompt(">");
if (name === "") break;
catNames.push(name);
}

console.log("The cat names are:");
for (const name of catNames) {
console.log(" " + name);
}

for loops over arrays

for...of iterates over items directly; a classic for loop gives you indexes.

Example:

const supplies = ["pens", "staplers", "flamethrowers", "binders"];

for (const item of supplies) {
console.log(item);
}

for (let i = 0; i < supplies.length; i++) {
console.log("Index", i, "is", supplies[i]);
}

includes() (equivalent of in)

.includes() tests membership and returns a Boolean.

Example:

const spam = ["hello", "hi", "howdy"];
console.log(spam.includes("hi")); // true
console.log(!spam.includes("cat")); // true (not in)

Simple pet checker:

const myPets = ["Zophie", "Pooka", "Fat-tail"];
const name = prompt("Enter a pet name:");
if (!myPets.includes(name)) {
console.log("I do not have a pet named " + name);
} else {
console.log(name + " is my pet.");
}

Destructuring assignment (unpacking)

You can unpack array items into separate variables in one line.

Example:

const cat = ["fat", "gray", "loud"];
const [size, color, disposition] = cat;
console.log(size, color, disposition); // fat gray loud

forEach with index (like enumerate)

.forEach() gives both index and item. You can also use .entries().

Example:

const supplies = ["pens", "staplers", "flamethrowers", "binders"];
supplies.forEach((item, index) => {
console.log("Index", index, "in supplies is:", item);
});

Random choice and shuffle

JavaScript has no built-in random.choice or random.shuffle, but they're easy to write.

Example:

const pets = ["Dog", "Cat", "Moose"];
const pick = pets[Math.floor(Math.random() * pets.length)];
console.log(pick);

// Fisher-Yates shuffle
const people = ["Alice", "Bob", "Carol", "David"];
for (let i = people.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[people[i], people[j]] = [people[j], people[i]];
}
console.log(people);

Augmented assignment with arrays

Operators like += and *= work with numbers and strings. For arrays, use .push() or spread.

Example:

let spam = "Hello";
spam += ", world!";
console.log(spam); // Hello, world!

let bacon = ["Zophie"];
bacon = Array(3).fill(bacon[0]);
console.log(bacon); // ['Zophie', 'Zophie', 'Zophie']

Array methods: indexOf, push, splice (insert)

  • indexOf(x) returns the index of x (first occurrence, or -1).
  • push(x) adds x to the end.
  • splice(i, 0, x) inserts x at index i.

Example:

const spam = ["hello", "hi", "howdy", "heyas"];
console.log(spam.indexOf("howdy")); // 2

spam.push("yo");
spam.splice(1, 0, "greetings");
console.log(spam);

Removing, sorting, and reversing

  • Remove by value: find with indexOf then splice.
  • .sort() sorts in place; .sort((a, b) => a.localeCompare(b)) for case-insensitive.
  • .reverse() reverses the array.

Example:

const spam = ["cat", "bat", "rat", "cat"];
spam.splice(spam.indexOf("cat"), 1);
console.log(spam); // ['bat', 'rat', 'cat']

const nums = [2, 5, 3.14, 1, -7];
nums.sort((a, b) => a - b);
console.log(nums); // [-7, 1, 2, 3.14, 5]

const animals = ["cats", "Ants", "dogs"];
animals.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
console.log(animals);

const pets = ["cat", "dog", "moose"];
pets.reverse();
console.log(pets); // ['moose', 'dog', 'cat']

Arrays across multiple lines

Arrays (and other bracketed expressions) can span lines naturally in JavaScript.

Example:

const spam = [
"apples",
"oranges",
"bananas",
"cats",
];

Short-circuiting and array safety

&& and || short-circuit: they may skip evaluating the right side, useful for safe index checks.

Example (avoid accessing undefined):

const spam = [];
if (spam.length > 0 && spam[0] === "cat") {
console.log("A cat is the first item.");
} else {
console.log("The first item is not a cat.");
}

You can also use optional chaining: spam[0]?.toLowerCase().


Magic 8-ball with an array

A cleaner Magic 8-ball uses an array of messages plus a random pick.

Example:

const messages = [
"It is certain",
"Ask again later",
"Very doubtful",
];

prompt("Ask a yes/no question:\n>");
console.log(messages[Math.floor(Math.random() * messages.length)]);

Sequence-like behavior: strings and arrays

Strings and arrays both support indexing, slicing (.slice()), .length, for...of, and .includes().

Example with a string:

const name = "Zophie";
console.log(name[0]); // 'Z'
console.log(name.slice(0, 4)); // 'Zoph'
console.log(name.includes("Zo")); // true
for (const ch of name) {
console.log("* " + ch + " *");
}

Mutable arrays; no tuples

Arrays are mutable (changeable). Strings are immutable. JavaScript has no tuple type, but Object.freeze() makes an array read-only (shallow).

Example:

const eggs = Object.freeze(["hello", 42, 0.5]);
// eggs[1] = 99; // silently fails (or TypeError in strict mode)

Converting between arrays and strings

Array.from() or spread splits a string to characters. .join() goes the other way.

Example:

console.log(Array.from("hello"));        // ['h', 'e', 'l', 'l', 'o']
console.log([..."hello"]); // ['h', 'e', 'l', 'l', 'o']
console.log(["h", "e", "l", "l", "o"].join("")); // 'hello'

References and shared arrays

Variables hold references to values; assigning one array variable to another copies the reference, so both names point to the same array.

Example:

const spam = [0, 1, 2, 3];
const eggs = spam; // same array
eggs[1] = "Hello!";
console.log(spam); // [0, 'Hello!', 2, 3]
console.log(eggs); // [0, 'Hello!', 2, 3]

Changing eggs changed spam because there is only one underlying array. Use [...spam] or .slice() for an independent copy.


Overall idea of the chapter

The chapter's main message is: JavaScript arrays work very similarly to Python lists. The main differences are method names (.push() vs .append(), .splice() vs del, .includes() vs in), .at() for negative indexes, and the lack of built-in tuples. Understanding references and copying is equally important in both languages.