Greeting JavaScript: What is an Array?10 min read

In a few previous parts, we’ve been working and handling some core topics in JavaScript. We are already known that a variable is a container for value and store that value such as username, phone number, etc…in memory piece by piece. However let’s imagine now we have a shopping list and we have to print out theme into the screen, if you had an intention to use variables for each of item, OK it’s fine but it is maybe waste of time and cumbersome, your code can look messy.

Or if you came up with an idea store all of them in a variable with a string and separate them by a comma. It is not really wise because remember string is the primitive value which means immutable, you cannot alter them when you already declared (but don’t confuse with the variable assignment). There are also 5 other primitive values, which are number, boolean, null, undefined and symbol. All of 6 kinds of values is not an object, have no method and immutable (I want to mention about those values just in case I have not talked about it).

There are also 5 other primitive values, which are number, boolean, null, undefined and symbol. All of 6 kinds of values is not an object, have no method and immutable (I want to mention about those values just in case I have not talked about it).

So, storing shopping list in a variable is not judicious. Do we have another way to do it more effectively, clearly? Of course, JavaScript has, that is the time when Array comes in handy, which is used to organize, maintain and store something like an a…shopping list. Suppose we have a shopping list like this:

Shopping list:

  • Apple
  • Bread
  • Milk
  • Water
  • Toothpaste

With array, we will store this list like this:

Create an array

var shoppingList = ["Apple", "Bread", "Milk", "Water", "Toothpaste"];
// ["Apple", "Bread", "Milk", "Water", "Toothpaste"]

Array literal

Create an array is simple, one way you can create this by an array literal. Which create an array by wrapping items into square brackets [ ] (like the example above). I will make a list here to help you get a better visualization:

  • The array is created by wrapping items inside square brackets [ ].
  • In the example array above, each item is an element of an array.
  • Not just storing string, array can store different data types such as number, boolean, object, function, nested array, etc…

Array constructor

This is the alternative way lets you create an array in JavaScript, with kind of syntax below:

var score = new Array();
console.log(score); // []

Create a new variable and assigns to it the syntax new Array() and a new array has been initialized.

We’ve created an array with empty element because we didn’t pass into this array any value. If you wanted to give it some values, no need to use square brackets, just pass the values you want to convey into the parentheses:

var score = new Array(1, 2, 3);
console.log(score); // [1, 2, 3];

var string = new Array("A string", true, 12, undefined, null);
console.log(string); // ["A string", true, 12, undefined, null]

But JavaScript also let you omit the new keyword when you create array constructor if you wanted.

var tvShow = Array("Rick and Morty", "Mr Robot", "Silicon Valley");
console.log(tvShow); // ["Rick and Morty", "Mr Robot", "Silicon Valley"]

Manipulate Array’s Element

Array’s Length Property

In order to know how many elements are existing in your array, we use array.length property. The value numerically always greater than array’s highest index, because we have zero-based index but array.length will count it normally.

var characters = ["Jessica", "Morty", "Noob-Noob", "Zeep", "Rick", "Scary Terry", "Beth", "Jerry", "Summer", "Poopybutthole", "BirdPerson"];
console.log(characters.length); // 11

Access Elements in an Array

Now let’s open console and see the output of the example array:

var shoppingList = ["Apple", "Bread", "Milk", "Water", "Toothpaste"];
// ["Apple", "Bread", "Milk", "Water", "Toothpaste"]

As you can see, our array has 5 items correspond with 5 elements in array. And, remember, the first element in an array start at index 0 or we called zero-based index as we did with string before (refer some previous articles to learn more), which means if you want to get the “Apple” in this array, simply you can do like this:

shoppingList[0]; // "Apple"

// Or save the value you want to return in a new variable:
var oneElement = shoppingList[2];
console.log(oneElement); // "Milk"

Replace/Update Elements in an Array

This is the way you can access and get the value of an element in an array by using square brackets that you want, which called bracket notation. You can update the value of elements inside an array by the same way:

var rainbow = ["Red", "Orange",	"Black", "Green", "Blue","Indigo", "Violet"];
rainbow[2] = "Yellow";
// ["Red", "Orange", "Yellow", "Green", "Blue",	"Indigo", "Violet"]

The element at the index 2 has been replaced, “Black” to “Yellow”.

Add elements to an array

Add element to the beginning

When you want to manipulate elements on an array, such as changing element, replace or update a new array list. You need to use array method(s). There are plenty of methods that integrated with arrays in JavaScript to help us deal with it. But first, in this article, I want to mention those fundamentals methods that we must get accustomed to first.

To add the element to the beginning of an array, simple we just use unshift() method, inside parentheses is/are element(s) that you want to add to the array:

var fruits = ["Orange", "Banana", "Apple"];
// ["Grape", "Orange", "Banana", "Apple"];

See, Grape has been added to the first position of this array. But when you use unshift(), your original array would be mutated and changed. Which we called destructive method. There are also a lot of methods that help us manipulate array but will not mutate or change the original array, which is non-destructive (I will cover some of those in this article, scroll down to see, but some others I will put away those in Functional Programming or later section).

Add element the the end

Likewise, we have push() method to add the element to the end of the array and it will mutate your original array.

var fruits = ["Orange", "Banana", "Apple"];
// ["Orange", "Banana", "Apple", "Strawberry"];

Delete element from the beginning

We utilize unshift() method to add element to the beginning of an array. By removing “un”, we have shift() method to eliminate the first element in the array and it no need to take any value:

var fruits = ["Orange", "Banana", "Apple"];
// ["Banana", "Apple"];

Delete Array’s Element

Delete element from the end

We use pop() method to remove the last element in an array, alike, no needs the take any value:

var fruits = ["Orange", "Banana", "Apple"];
// ["Orange", "Banana"];

Delete, update, replace particular element

Upwards, we added, deleted from the beginning and the end of the array, but we not yet talked about the arbitrary elements that we want to modify. We have some ways to do it, but most handy is splice() method. The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements. However, this method is a little more complex than the previous ones, splice() method has the syntax like this:

array.splice(start, deleteCount, item1, item2...)
  • start: origin with 0, pick up the position you want to splice, like array index, if you want to splice at the second element, you could do like this: array.splice(1)
  • deleteCount (optional): Define how many elements you want to delete, from the given index, eliminate left to right, for instance, delete 1 element from the index 3: array.splice(3, 1)
  • item (optional): replace or add elements to array begin with start index.

For example, we have an array:

var numbers = [2, 3, 4, 5, 6];

Our task is delete the number 4 and replace nothing, with splice() method it can be done like this:

var numbers = [2, 3, 4, 5, 6];
var removeNumber = numbers.splice(2,1);
// [2, 3, 5, 6]
// [4]

Here we have another array:

var names = ["Simon", "Elliot", "Quincy", "Dale"];

We want to remove the second element and replace it by “Alison” and that’s it:

var names = ["Simon", "Elliot", "Quincy", "Dale"];
names.splice(1, 1, "Alison");
["Simon", "Alison", "Quincy", "Dale"];

With those arrays, we can easily see the index of element that we want to reach, but if we have an array with a bunch of elements, it’s hard to find out the element by just looking. JavaScript offers to us a method that can find exactly the position of this element, that is indexOf() method, if the value is not presented, it will return -1:

var characters = ["Jessica", "Morty", "Noob-Noob", "Zeep", "Rick", "Scary Terry", "Beth", "Jerry", "Summer", "Poopybutthole", "BirdPerson"];
console.log(characters.indexOf("Scary Terry")); // 5

Now let’s try to remove an element which has the value “Simon” and replace it with “Anna”:

var names = ["Jessica", "Morty", "Noob-Noob", "Zeep", "Rick", "Scary Terry", "Beth", "Jerry", "Summer", "Poopybutthole", "BirdPerson", "Simon", "Elliot", "Quincy", "Dale"];

First we have to create a variable that check the position of “Simon” in this array:

var simonPosition = names.indexOf("Simon");
console.log(simonPosition); // 11;

Now we have the position, we can use splice the remove it, but before we do it, we need to use if condition to make sure that the value “Simon” is presented, then splice the array to remove this element and replace it with “Anna”:

if(simonPosition > -1){
names.splice(simonPosition, 1, "Anna");

Now wrap all of ’em together:

var names = ["Jessica", "Morty", "Noob-Noob", "Zeep", "Rick", "Scary Terry", "Beth", "Jerry", "Summer", "Poopybutthole", "BirdPerson", "Simon", "Elliot", "Quincy", "Dale"];
var simonPosition = names.indexOf("Simon");
if(simonPosition > -1){
names.splice(simonPosition, 1, "Anna");
// ["Jessica", "Morty", "Noob-Noob", "Zeep", "Rick", "Scary Terry", "Beth", "Jerry", "Summer", "Poopybutthole", "BirdPerson", "Anna", "Elliot", "Quincy", "Dale"]

So, we did it! Sometimes just have to take a look a little bit to see the index of an element. But in most cases, it’s better for us to use indexOf() method to find out the accurate position of an element. Combining with splice() method, we removed the element with the value “Simon” and replaced it with “Anna” easily and accurately.

Link two or more different array

As I said earlier, there are two ways to manipulate with arrays. One, destructive, which means the original array will be mutable and changeable. But with the elegant of functional programming, destructive is not accepted. That is the factor why we need to use the non-destructive method instead, which is provided in JavaScript.

Concat method()

With the limitation of this article, we just mention a little bit about non-destructive method (we will cover in deep about functional programming and non-destructive method in the later sections), which is concat() method. This method helps you link 2 or more different arrays into a single one, without changing and mutating the original array.

var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
var array3 = array1.concat(array2);
console.log(array3); // [1, 2, 3, 4, 5, 6]
console.log(array1); // [1, 2, 3] // Still immutable
console.log(array2); // [4, 5, 6] // Still immutable

Array nested Array

Array, like many other objects, it can be nested. That means with one primary array, you can create the different other arrays inside it seperating by a comma. Look at this example:

var array = [
[1, 2, 3],
[true, false, undefined],
["a", "b", "c"]

This code above is the typical example of a nested array, and do you know how we call this kinda array? Nested array, or more specifically, two-dimensional array. We have the outer array which obtains 3 different arrays inside it. But the question is, how we can get the data from those arrays? For instance, we want to access the value “2” on this array below, just manipulate like many other arrays:

var array = [
[1, 2, 3],
[true, false, undefined],
["a", "b", "c"]
console.log(array[0][1]); //2

From outside to inside, first you need to access the first inner array which is [1, 2, 3] by using array[0] then access the second element of this array by array[0][1].

However, you still can nest many arrays as you want into an array if you wanted, but the downside is with too many arrays nested in other, it’s not easy to practice and bulky to maintain.


From now on, you’ve equipped for yourself the fundamental of the array in JavaScript, like how to create an array, access to its value, manipulate them, what is a nested array and what is the destructive method and non-destructive method. We will dive deeper about array and functional programming in some later articles, I hope to see you there. Happy coding! 🙂

Facebook Comments

Previous Article
Next Article

Leave a Reply

2 Comment threads
1 Thread replies
Most reacted comment
Hottest comment thread
2 Comment authors
Learn To Code TogetherBrumfield Recent comment authors
newest oldest most voted
Notify of

This article is really practical, thank you!

Sign up for newsletter

* indicates required