; PSY 1903
PSY 1903 Programming for Psychologists

Arrays

In our discussion of data types, we learned about scalar data types like Strings, Numbers, and Booleans. These data types are considered scalar because they represent one single value.

Now lets look more closely at compound data types that can hold multiple values starting with Arrays.

An Array can store multiple values (of the same or mixed data types), separated by commas within square brackets. Examples:

// An Array of Numbers
let ages = [45, 23, 28, 35, 35];

// An Array of Strings
let names = ['Alice', 'Jamal', 'Avi', 'Kyle'];

// An Array can contain other Arrays
let numbers = [1, 2, 3, [8, 9, 10]];

// An Array of mixed data types
let mixed = ['a', 'b', 1, 2, [true, false]];

Array operations

We can access items in an Array using square brackets ([]) and the index position of an item in the array. The first item in an Array is at the 0th index position, the next item is at 1, etc. (The practice of starting counting at 0 instead of 1 is common in programming).

Some examples of accessing items in an Array by their index position:

let names = ['Alice', 'Jamal', 'Avi', 'Kyle'];
console.log(names[1]); // Jamal
console.log(names[0]); // Alice
console.log(names[3]); // Kyle

Observe what happens if you use an index position goes beyond the bounds of the Array:

console.log(names[4]); // undefined because there is no 4th element

One way to add an item to the end of an Array is to use the push method:

let names = ['Alice', 'Jamal', 'Avi', 'Kyle'];
names.push('Booker');
console.log(names); // Alice, Jamal, Avi ,Kyle, Booker

One way to reassign the value of an array is to use square bracket notation:

let names = ['Alice', 'Jamal', 'Avi', 'Kyle'];
names[1] = 'Sam';
console.log(names); // Alice, Sam, Avi, Kyle

Learn more...

In the above examples, we covered a small sampling of the manipulations you can do with JavaScript Arrays. We’ll explain other manipulations as we encounter the need for them, and you can also skim the following guide: MDN JavaScript Array basics.