Arrays
In Python, you store a list of things like this:
fruits = ["apple", "banana", "cherry"]
JavaScript has the same thing — it is called an array:
let fruits = ["apple", "banana", "cherry"]
Same square brackets. Same idea. You already know this.
Accessing items
Items are numbered starting from zero — same as Python:
let fruits = ["apple", "banana", "cherry"]
console.log(fruits[0]) // apple
console.log(fruits[1]) // banana
console.log(fruits[2]) // cherry
The length
.length tells you how many items are in the array:
let fruits = ["apple", "banana", "cherry"]
console.log(fruits.length) // 3
Python's equivalent is len(fruits) — same idea, different look.
Adding an item — .push()
.push() adds an item to the end of the array:
let fruits = ["apple", "banana"]
fruits.push("cherry")
console.log(fruits) // ["apple", "banana", "cherry"]
console.log(fruits.length) // 3
Python's equivalent is fruits.append("cherry").
Arrays of objects
Arrays can hold anything — including objects. An object in JavaScript is like a dictionary in Python:
# Python
patients = [
{"name": "Alice", "age": 24},
{"name": "Bob", "age": 31}
]
// JavaScript
let patients = [
{ name: "Alice", age: 24 },
{ name: "Bob", age: 31 }
]
Access a field with a dot: patients[0].name gives "Alice". Python uses patients[0]["name"] — JavaScript uses a dot instead.
Challenge
Open the browser console (F12 → Console). Create an array of five things — anything you like. Print the third item. Print the length. Push two more items on and print the length again. Does it update?