DEV Community

Kevin O'Shaughnessy
Kevin O'Shaughnessy

Posted on

JavaScript Arrays - Index Values and Adding to an Array

Intro

Arrays are common JavaScript variables which hold more than 1 value rather than just using separate variables. For example, using basic JavaScript, we could list each value independently or we could list them in an array.

const fruit1 = "apple";
const fruit2 = "orange";
const fruit3 = "grape";
const fruit4 = "strawberry";

const fruit = ["apple", "orange", "grape", "strawberry"];

Arrays can be manipulated -added to, subtracted from, or render only certain values. Arrays can also be listed vertically, for clarity, when needed:

const fruit = [
"apple",
"orange",
"grape",
"strawberry"
];

Index Values

Each array item has its own index number corresponding to its place in the array.[1] This numbering system starts at 0 and goes up to as many objects are in the array. For example, the index of "apple" is 0, so fruit[0] = "apple". Other values include:

fruit[1] = "orange"
fruit[2] = "grape"
fruit[3] = "strawberry"

So, this array has 4 values but only goes up to the number 3 because the index value of the first item is always 0.

Adding to an Array

There are a couple methods for adding items to an array. We can use push() to add something to the end of an array. To add something to the beginning, we would use the unshift method.[2] For our example, this would look like the following:

Adding to the End
const fruit = ["apple", "orange", "grape", "strawberry"];
fruit.push("dragon fruit")
console.log(fruit) would show the value:
["apple", "orange", "grape", "strawberry", "dragon fruit"]

Adding to the beginning
const fruit = ["apple", "orange", "grape", "strawberry"];
fruit.unshift("dragon fruit")
console.log(fruit) would show the value:
["dragon fruit", "apple", "orange", "grape", "strawberry"]

In each of these cases, the original array is being modified, we are not creating new arrays.


Sources Consulted:

  1. https://www.w3schools.com/js/js_arrays.asp
  2. Fluke, Joshua. '5 Must Know Interview Questions for Javascript!' https://www.youtube.com/watch?v=6Wzj7kxfRdI

Top comments (0)