- Arrays and index access
- Undefined
- Null and how to treat it
In this section, we’ll cover three more types that are very common in JavaScript programs:
Arrays: sequences of values
undefined: a special value that means "nothing was assigned"
null: another special value that means "intentionally empty"
Arrays and index access
An array is a type that can hold multiple values in a list.
You create an array by using square brackets
[] and separating the items with commas.Here’s a basic example:
const numbers = [10, 2, 88] console.log(numbers)
This prints:
[ 10, 2, 88 ]
You can store anything in an array, not just numbers:
const things = ["apple", 42, true] console.log(things)
This prints:
[ 'apple', 42, true ]
To access a specific item in the array, we use an index. The index is the position of the item, starting from 0.
So in this array:
const colors = ["red", "green", "blue"]
colors[0] is "red"
colors[1] is "green"
colors[2] is "blue"Let’s try:
const colors = ["red", "green", "blue"] console.log(colors[0]) console.log(colors[1]) console.log(colors[2])
This will print:
red green blue
You can assign a value to a specific index of an array
const colors = ["red", "green", "blue"] colors[1] = "yellow" console.log(colors)
This will print:
[ 'red', 'yellow', 'blue' ]
You can use any natural number as an index, even one stored in a variable
const i = 1 const colors = ["red", "green", "blue"] console.log(colors[i])
This will print:
green
But if you try to access an index that doesn’t exist, you will get
undefined:const colors = ["red", "green", "blue"] console.log(colors[3])
This prints:
undefined
What's that??
undefined
The special value
undefined means “no value was assigned”.If you create a variable but don’t give it a value, it will be
undefined:const name console.log(name)
This prints:
undefined
Because we didn’t assign anything to
name, JavaScript sets it to undefined by default.As seen before, you can also get
undefined when you access an array index that doesn’t exist:const fruits = ["banana", "apple"] console.log(fruits[2]) // There is no index 2
This prints:
undefined
null and how to treat it
null is also a special value. It means “nothing is here, and I did that on purpose.”Unlike
undefined, which is automatic, null is something you set yourself.For example:
const currentUser = null console.log(currentUser)
This prints:
null
Why use
null? Maybe you expect a value later, but it’s not ready yet:let winner = null // Later in the program: winner = "Alice" console.log(winner)
This prints:
Alice
So
null is useful when you want to say, for example, “There should be something here later, but right now it’s empty.”