Arrays and Lists in JavaScript

An array or list is a way to store multiple variable in one variable, this can be used to store a list of related variables or just a list of numbers. Lists can also be joined together, split apart, or just accessed one index at a time. An index refers to the position in the list where a certain variable sits. Lists are indexed from 0, so the first element is at index 0 then the next is at index 1 and so on.

The code below shows creating a list called ‘myList’ with the number 1 through 4. The numbers are contained within square brackets ‘[..]’ which is how arrays are created in JavaScript. The elements of the array are separated by commas, to distinguish different elements. The log statement then gets the 0th index of the array, by using the name of the array followed by square brackets and the number of the index. The 0th index is the first number in the list, so this log statement will print the number 1.

You can also find out how long an array is by using the ‘length’ property of the array. The length of the array will result to the number of elements within the array. Properties and functions of objects in JavaScript are called using a dot separator. The result of the below code will be the number 4 being logged, as there are 4 numbers in our array.

As JavaScript is dynamically typed it means we are not restricted with what data types can be stored in a single array. The below example shows an array that contains a number, two string, and boolean. The log statement will print the boolean value ‘true’ and that is the 3rd index in the array, even though it is the 4th element due to list indexes starting at 0.

Leave a Reply