Arrays

Arrays

  • Used to when you are working with a list of values that are related to each other

  • Use square brackets to create an array (this is also how you quickly recognize arrays)

  • Values in an array are separated by commas


Creating an Array

  • We can store variables just like any other data type

  • You can create that doesn’t initially contain any values, this is called an empty array

  • An array can also be created with initial values

  • Square brackets are a means of identifying if a variable is an array

// declare a variable as an empty array
const numbers = []

// or you can declare an array with initial values
const streets = ['Broadway', 'Houston', 'Grand']

Values in an Array

  • Values in an array are accessed as if they are in a numbered list

  • Arrays are zero based meaning the 1st “value” in an array is at position (index) 0, the 2nd element is at position 1, and so on

  • You access the value of an element in the array by passing the index of the item in square brackets

const streets = ['Broadway', 'Houston', 'Grand']

// access the 2nd street listed in the array which is at index 1
const streetTwo = streets[1]

Accessing Values in an Array

  • You can access a value of an array by referencing its index (i.e. its order within the array)
// declare a variable called chipmunks and use it to store
// an array of names
const chipmunks = ["Alvin", "Simon", "Theodore"]

// reference the first value in the array
// here we pass in a zero, since that represents the first
// element (value) in an array

const bandMember = chipmunks[0] //> the value stored in bandMember is "Alvin"

Changing Values in an Array

  • You can change a value in an array by referencing the value and then changing the value using an = (equal sign)
// declare a variable called newEditionMembers and use it to store
// an array of names

const newEditionMembers = ["Ricky Bell", "Michael Bivins", "Bobby Brown", "Ronnie DeVoe", "Ralph Tresvant"]

// We are going replace Bobby Brown with Johnny Gill
// by referencing the 3rd element of the array by using index 2
// and then use assignment (just an equal sign) to change
// the value to Johnny Gill

newEditionMembers[2] = "Johnny Gill"

Array Examples

JS Bin on jsbin.com

Arrays are a flexible and powerful feature of JavaScript (and other programming languages as well). Click here for more information about Arrays