Comp 101 Arrays: Overview

All about arrays!

Arrays are one of the most useful concepts in computer science. Arrays are objects which can store other objects... which can be a little confusing to conceptualize at first.

Let's think about an egg carton...

An egg carton is itself an object, whose purpose is to store other objects (the eggs). We can think about the egg carton as our array and the eggs inside as the values stored at different indices in our array!

Here a is our "egg carton" and the numbers at indices 0-7 are our eggs! Note that our first index here is 0 not 1.

Array Syntax

Now that we know what an array is, let's look at how to set one up!

let arr0: number[]; // this syntax will declare a new number array without intializing it
let arr1 = []; // this syntax will create a new empty array
let arr2 =[1, 2, 3] // this syntax will create a new number array with the values 1, 2, 3 stored in its first three indices

// we can fill in the values of an array by directly addressing the indices we want to change
arr1[0] = 1;
arr1[1] = 2;
arr1[2] = 3;

// or we can use a loop to fill in desired values
arr0 = [];
let i = 0;

while ( i < arr0.length ) { // the .length operator tells us how many elements are currently in the array!
     arr[i] = i+1;

// the above loop will set arr0's first three indices to 1, 2, 3

Useful Array Operations