JavaScript 101-#9 – Arrays Pt1

Table of Contents

Today’s issue of JavaScript 101 will be all about arrays. If you read the post about data types covering arrays, you should already know at least the basics. If not, don’t worry. We will practice creating one and n-th dimensional arrays at the beginning just for warming up. Then, we will move to methods that can be applied to arrays and how to use them. Let’s start.

Creating arrays

First thing we will do, is to practice simple creating arrays. You can create an array in three ways. First is through Array constructor, which I suggest you not to use, next is declaring empty array and add items later. The last way is to go through second way, but do it do it all in the same time. Below are examples of all three ways.

JavaScript:

// Array constructor – don't use this
var arr1 = new Array();
arr1[0] = “first item”;
arr1[1] = “second item”;
arr1[2] = 3;
console.log(arr1); // result - [“first item”, “second item”, 3]
var arr2 = new Array(“first item”, “second item”, 3);
console.log(arr2); // result - [“first item”, “second item”, 3]

// Empty array first
var arr3 = [];
arr3[0] = true;
arr3[1] = 1483;
arr3[2] = “dodecahedron”;
console.log(arr3); // result - [true, 1483, “dodecahedron”]

// All at once
var arr4 = [“front”, “HTML”,”back”,”PHP”, false];
console.log(arr4); // result - [“front”, “HTML”,”back”,”PHP”, false];

Accessing items

When we are in coding, let’s also practice accessing individual items inside array. In this exercise we will also create few multidimensional arrays. Remember that items inside array start with index 0. In case of multidimensional arrays, you access items by using multiple indexes in separated square brackets. For example, in two dimensional array, first index marks the array and second the item.

JavaScript:

var multiArr1 = [[“don't”,”make”, “me”, true], [14, 15, 92, 65, 35]];
console.log(multiArr1[1][3]); // result – 65
var multiArr2 = [[“Monday”, 51],[“Tuesday”, 895],[“Friday”, 13]];
console.log(multiArr2[2][0]); // result - “Friday”
console.log(multiArr2[0]); // result - [“Moday”, 51]

// creating empty array first
var multiArr3 = [];
multiArr3[0] = []; // create the first nested array to populate it later
multiArr3[0][0] = "Session";
multiArr3[0][1] = 5986;
multiArr3[0][2] = false;
multiArr3[1] = []; // create the second nested array
multiArr3[1][0] = false;
multiArr3[1][1] = true;
multiArr3[2] = []; // create the third nested array
multiArr3[2][0] = "end";
console.log(multiArr3[0]); // result - ["Session", 5986, false]
console.log(multiArr3[1]); // result - [false, true]
console.log(multiArr3[2]); // result - [“end”]

If you want to “print” content of the whole array into the console instead of this line-by-line method, you can use “for” loop. We didn’t cover loops yet, so I will not bother you with it right now. However, you should at least see the example to get ready for future lessons.

JavaScript:

// create multidimensional array on one line
var multiArr3 = [["Session", 5986, “game”], [false, true], [“end”]];
// loop through the array and print individual items into console
for (var i = 0, j = multiArr3.length; i < j; i++) {
 for (var k = 0, l = multiArr3[i].length; k < l; k++) {
 console.log(multiArr3[i][k]);
 }
}
// result: 
"Session", 5986, “game”, false, true, “end”

– note: Every item will be on separate line. I used the one-liner to save some space.

Methods

What do you think about the loop? Did you understand it? Anyway, let’s move forward to our main topic … Methods!

pop() and push()

First two methods we will talk about are pop() and push(). pop() method will remove the last item inside array and it will also return it, so if you use console.log() or other command, you will see removed item. This method doesn’t take any parameter. Just to mention, all methods we will cover today changes the original array.

JavaScript:

// pop() example
var arr = [“end”, true, “scissors”, 159, “game”];
console.log(arr.pop()); // result - “game”
console.log(arr); // result - [“end”, true, “scissors”, 159];
console.log(arr.pop()); // result - 159
console.log(arr); // result - [“end”, true, “scissors”];

push() method takes as many parameters as you want and then it will add these items on the end of array. It will return the length of new array.

JavaScript:

// push() example
var arr = [“end”, true, “scissors”, 159];
console.log(arr.push(“Daidal”, 45)); // result - 7
//console.log(arr); // result - ["end", true, "scissors", 159, "game", "Daidal", 45] 
console.log(arr.push(892)); // result - 8
//console.log(arr); // result - ["end", true, "scissors", 159, "game", "Daidal", 45, 892]

shift() and unshift()

shift() and unshift() methods works in similar fashion like pop() and push() except one thing. These two start at the beginning of array. shift() will remove and return the first element in array. unshift() will add new element on the index zero (first position) in array and return the new length. When new item is added to array, indexes for the previous items is moved by one (or more in case of more added items).

JavaScript:

// shift() example
var arr1 = [false, “fruit”, “Gecko”];
console.log(arr1.shift()); // result - false
console.log(arr1); // result - [“fruit”, “Gecko”]

// unshift() example
var arr2 = [false, “fruit”, “Gecko”];
console.log(arr2.unshift(“object”)); // result - 4
console.log(arr2); // result - [“object”, false, “fruit”, “Gecko”];

Changing items

If you want change some item inside an array, all you have to do is to use the name and index like when accessing that item, then use equal sign and write new value.

JavaScript:

var arr3 = [“Internet”, “thing”, “Carpenter”, “ghost”];
arr3[1] = 0;
arr3[0] = “box”;
console.log(arr3); // result - ["box", 0, "Carpenter", "ghost"]

delete

Delete use a bit different syntax then previous methods. In order to delete an item, you use “delete” keyword and name of array followed by square brackets containing index of that item. No dot is used.

JavaScript:

var arr3 = ["Internet", "thing", "Carpenter", "ghost"];
delete arr3[0];
console.log(arr3); result - [undefined, "thing", "Carpenter", "ghost"]

– note: Delete command actually doesn’t delete the item, it will only change it to undefined. Better practice is to use pop() method above or splice() below.

splice()

This method can be used to either add items to array or remove them. To remove item you have to use two parameters. First says on which position (index) should removing start and the second how many elements you want to remove.

JavaScript:

// removing items
var arr4 = [“gremlin”, “rock”, “paper”, “baron”];
arr4.splice(1, 1); // this will remove second item
console.log(arr4); // result - ["gremlin", "paper", "baron"] 
var arr4 = [“gremlin”, “rock”, “paper”, “baron”];
arr4.splice(1, 3); // this will remove 3 items, beginning on index 1
console.log(arr4); // result - [“gremlin”]

– note: As you can see, items are completely removed. Nothing is set to ‘undefined’.

On the other hand, if you want to add items you will use same syntax plus the items you want to add. Same as with unshift(), when you add item to array, the rest will just move the next index.

JavaScript:

// adding items
var arr5 = [2, “wins”];
arr5.splice(1, 0, “thrown”, 65, 23); // start on index 1, remove 0 items and add “thrown”, 65, 23
console.log(arr5); // result - [2, "thrown", 65, 23, "wins"]

// you can also replace item by changing the second parameter
var arr5 = [2, “wins”];
arr5.splice(1, 1, “thrown”, 65, 23); // start on index 1, remove 1 item (“wins”) and add “thrown”, 65, 23
console.log(arr5); // result - [2, "thrown", 65, 23]
var arr6 = [false, 65, 89, “alf”, “house”];
arr6.splice(2,3, “get”, true, “ball”); // start on index 2, remove 3 items and add “get”, true, “ball”
console.log(arr6); // result - [false, 65, "get", true, "ball"]

Summary

That’s all for today. First part of arrays is behind us and all it took was only slight headache and sore fingers. In the next part we will finish by learning about few remaining methods. I hope you understood everything well. In case of any problems, I’m here to help. AD

If you liked this article, please subscribe so you don't miss any future post.

If you'd like to support me and this blog, you can become a patron, or you can buy me a coffee 🙂

By Alex Devero

I'm Founder/CEO of DEVERO Corporation. Entrepreneur, designer, developer. My mission and MTP is to accelerate the development of humankind through technology.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.