Lists vs Arrays
Working with ordered collections in JavaScript
Introduction
In this lesson, you'll learn about lists vs arrays in JavaScript. Coming from Python, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In Python, you're familiar with working with ordered collections in javascript.
JavaScript has its own approach to working with ordered collections in javascript, which we'll explore step by step.
The JavaScript Way
Let's see how JavaScript handles this concept. Here's a typical example:
const nums = [1, 2, 3, 4, 5];
// Add / remove
nums.push(6); // add to end
nums.unshift(0); // add to front
nums.pop(); // remove last
nums.shift(); // remove first
// Slicing
const half = nums.slice(1, 4);
const rev = [...nums].reverse();
// Functional methods
const doubled = nums.map(n => n * 2);
const evens = nums.filter(n => n % 2 === 0);
// Destructuring with rest
const [first, ...rest] = nums;
const [...init, last] = nums; // not standard — use sliceComparing to Python
Here's how you might have written similar code in Python:
nums = [1, 2, 3, 4, 5]
# Add / remove
nums.append(6)
nums.insert(0, 0)
nums.pop() # removes last
nums.pop(0) # removes first
# Slicing
half = nums[1:4]
rev = nums[::-1]
# Comprehensions
doubled = [n * 2 for n in nums]
evens = [n for n in nums if n % 2 == 0]
# Unpacking
first, *rest = nums
*init, last = numsYou may be used to different syntax or behavior.
push/pop ≈ append/pop, shift/unshift ≈ pop(0)/insert(0,x)
You may be used to different syntax or behavior.
slice() is not in-place; reverse() mutates (use [...arr].reverse())
You may be used to different syntax or behavior.
Destructuring rest (...) ≈ Python *rest unpacking
You may be used to different syntax or behavior.
No slice step — use filter or loop for step > 1
Step-by-Step Breakdown
1. Adding and Removing
JS arrays have push/pop for the end and shift/unshift for the front.
lst.append(x)
lst.insert(0, x)
lst.pop()
lst.pop(0)arr.push(x);
arr.unshift(x);
arr.pop();
arr.shift();2. Slicing
arr.slice(start, end) works like Python's list[start:end]. Note: reverse() is in-place!
nums[1:4]
nums[::-1]nums.slice(1, 4)
[...nums].reverse() // spread first to avoid mutation3. Destructuring
Array destructuring with rest (...) works like Python's *rest unpacking.
first, *rest = numsconst [first, ...rest] = nums;Common Mistakes
When coming from Python, developers often make these mistakes:
- push/pop ≈ append/pop, shift/unshift ≈ pop(0)/insert(0,x)
- slice() is not in-place; reverse() mutates (use [...arr].reverse())
- Destructuring rest (...) ≈ Python *rest unpacking
Key Takeaways
- push/pop ↔ append/pop, shift/unshift ↔ insert/pop(0)
- slice() doesn't mutate; reverse() does
- Array destructuring ≈ sequence unpacking