skip to content
Dev Journal

Intro to Array

/ 2 min read

Imagine you’re about to head to the grocery store, and you’ve got a list of items you need. In JavaScript, you can think of this “list” as an array. Arrays are special objects designed to hold list-like data.

Creating Arrays

Creating an array is as simple as using square brackets:

const emptyArray = []

You can also add values right from the start, separating each item with a comma:

const groceriesToBuy = ["cabbage", "tomate sauce", "salmon"]

Array values

Arrays are pretty versatile. They can hold any valid JavaScript value, such as:

  • Strings: ['One', "Two", "Three"]
  • Numbers: [1,2,3]
  • Boolean: [true, false, true]
  • Objects: [{name: "Reza"}, { name: "Iqlima"}]
  • Other arrays: [[1,2,3], [4,5,6]]

Reading and Formatting Arrays

For better readability, you can write each item on a new line:

const groceriesToBuy = [
"cabbage",
"tomato sauce",
"salmon"
]

Checking Array Length

Arrays come with handy properties and methods. To find out how many items are in an array, use the length property:

const numbers = [1,2,3,4]
console.log(numbers.length) // 4

Accessing Array items

To access an item in an array, use the array name followed by the item’s index in square brackets:

const strings = ["one", "two", "three", "four"]
const firstItem = strings[0] // "one"
const secondItem = strings[1] // "two"

Remember, indexes start at 0, so the first item is at index 0, the second at index 1, and so on. If you try to access an index beyond the array’s length, you’ll get undefined:

const tenthItem = strings[9]
console.log(tenthItem) // undefined

Accessing the Last item

To grab the last item in an array, use array.length - 1

const lastItem = strings[strings.length - 1] // "Four"

You can also get other items from the end of the array:

const secondLastItem = strings[strings.length - 2] // "Three"
const thirdLastItem = strings[strings.length - 3] // "Two"

Modifying Array items

Changing an item is straightforward. Just assign a new value to the desired index:

strings[0] = "1"
console.log(strings) // ["1", "two", "three", "four"]

If you assign a value to an index beyond the current length of the array, JavaScript will file the gap with undefined

strings[10] = "ten"
console.log(strings) // ['1', 'Two', 'Three', 'Four', undefined, undefined, undefined, undefined, undefined, undefined, 'Ten']