Array lists - ENTERING THE SECOND REALM - JavaScript in Plain Language (2015)

JavaScript in Plain Language (2015)

PART II: ENTERING THE SECOND REALM

2.9 Array lists

Strings versus arrays

Up to now we have been working mostly with string values. Here’s an example of a string value assigned to variable x which has already been initialized by var :

x = "orange";

As far character mapping is concerned, o is the first character located in position zero, r is the second character located in position 1, a is the third character located in position 2, etc.

Here’s another example:

y = "orange banana apple";

In the above example, b is the eighth character (we must count the white spaces) and it’s located in position number 7 (0,1,2,3,4,5,6,7).

What if we wanted to count the words instead of counting the number of characters?

We can’t separate the words with individual quotes because JavaScript will throw an error:

y = "orange" "banana" "apple"; <-- this would not work.

And even if we separate them with commas,

y = "orange","banana","apple";

JavaScript will first assign y to orange, then reassigns y to banana, and finally to apple which, in the end, will be the only value stored in y.

So in string values, mapping is limited to individual characters. The whole string is considered one unit of multiple characters.

· In short, if we want to save words as separately independent units on a variable, we need to use a different data type because string will not do it. One of such types is called an array (there are others).

The difference between an array type and a string type is that we can store individual words. Another advantage of an array is that we can also store values of type number, as well as other types such as functions, objects and Booleans in individual packets of the same variable.

Just like a string value, in arrays we also address each position numerically starting from location zero. In fact, a string value is a very simple array of individual characters.

Think of an array as a pocket folder.

Each pocket is sequentially labeled and in each pocket, we can store anything we want.

To retrieve the contents of each pocket we call the array with bracket syntax and use the location number to address the data we are trying to fetch.

Array syntax

To declare a value of type array we use a pair of square brackets:

var x = [ ];

You may read on the web about bracket syntax as being referred to as array syntax and the reason is that bracket syntax comes from the idea of array pocket locations.

The above example is an empty array because it does not have any data inside of the brackets, but the square brackets have instructed the JavaScript interpreter to declare variable y as a type array.

Going back to our last string example, if we want to save individually independent words we can declare and assign variable y in the following manner:

var y = ["orange","banana","apple"];

Now if we call y’s location number 2, we get "apple" as a result:

y[2]; <-- it displays "apple"

or more implicitly:

console.log(y[2]); <-- it displays apple

Knowing that our array y has three values spanning from location zero to location 2, we can add more values to it by addressing subsequent locations. Example:

y[3] = "peach";

Now if we call variable y on the Console by typing y; we get:

["orange", "banana", "apple", "peach"]

What happens if we reassign one of the existing locations such as for example location zero?

y[0] = "grape";

We overwrite the previous value because we have just reassigned the location to a different value. The array will not shift positions to accommodate one more items, it just deletes the existing value by reassigning the location to something else.

Array y now still contains the previous number of values as follows:

["grape", "banana", "apple", "peach"]
"orange" was deleted.

Using push() and unshift() to insert elements into an array

As arrays get larger it becomes almost impossible to know how many items the array contains which makes it very difficult to add new items since when we add an item to a position in the array and this position is already filled, JavaScript replaces the new item with the old item. The old item is deleted from the array.

To prevent this deletion from happening, JavaScript has two mechanisms that help us add items to an array: push and unshift.

Push()

The most common way of adding new items to an array is by adding them to the very end of the list.

· The array method push() adds items to the very end of the list.

Do you remember how we appended characters to a string by using += ?

The problem with += is that it adds the new item to the last item as one unit (by attachment).

For example, in
var y =["orange","banana","apple","peach"];

If we write y += "cherry";

we will get "orange, banana, apple, peachcherry"

and that’s not what we want to accomplish in an array, right?
We want independent items.

· The correct syntax to add items to the end of an array is as follows:
y.push("cherry");

We call the array method push() with dot syntax and pass in "cherry" as a data argument. It works just like calling a function with an argument data.

Now the array contains one more element:

["orange", "banana", "apple", "peach", "cherry"]

Let’s add one more item, avocado:

y.push("avocado");

Now array y contains the following items:

["orange", "banana", "apple", "peach", "cherry", "avocado"]

The meaning of push:

Imagine a stack of bricks. When we place a new brick on the stack it pushes down the others because of its weight. The top of the stack is the last position of the array. We push it in order to insert a new item into the stack.

Now, if you visualize the array in a horizontal manner instead of vertically, the last item is on your right side.

We will use push() many times throughout the book since it is the most common way to insert new array items.

unshift()

The method unshift() adds items to the beginning of the array.

When we visualize the array vertically the beginning of the array is the very bottom of it, and horizontally, it is the left most side of the array.

Taking the last instance of array y from the previous topic as an example, let’s add blueberry to the beginning of the array:

y.unshift("blueberry");

Array y is now:

["blueberry", "orange", "banana", "apple", "peach", "cherry", "avocado"]

Notice how "orange" moved to position 1, or second item, to give way to "blueberry" as the new position zero.

The meaning of unshift:

In order to insert a new brick at the bottom of the stack, we need to unshift all the bricks up so that we can squeeze a new brick as the first item of the stack since the first item is at the bottom.

On the other hand, when we do a push to insert a new item to the top of the stack, we are actually shifting everything down as we push, even though there is nowhere to go at the bottom. (Shift is actually used to remove an item from the bottom as we will see later). When we remove the item the bricks get shifted down but they are not being pushed because we are not inserting a new item at the top of the stack. This is just to help you understand the terms and where they came from. Don’t worry about shift for now. I will cover it later.

Right now we know about push() and unshift().

Printing array items with a for loop

As you’ve probably noticed, the visual display of an array on the screen when we call it by name is in its raw visual format:

["blueberry", "orange", "banana", "apple", "peach", "cherry", "avocado"]

How do we display the items by themselves?

We can use the array length property, and a for loop, to do such thing.

The length property works just like it did for strings. We can find out the length of an array by attaching .length to the array variable name:

y.length; <-- it display the number 7

Now, as you remember from playing with the string "orange" earlier (Lab work 7), when we know the length of the item we are going to scan, we initialize a for loop in the following manner:

for(var i = 0; i < 7; i++) { do this stuff; }

However, for the most part we don’t know the length of the item we are trying to scan and that’s when .length comes to the rescue:

for (var i = 0; i < y.length; i++ ){ do this stuff; }

This last implementation is much more efficient because we don’t have to worry about redoing the loop if the array ever changes length when we delete or add new items to it.

The rest of the code needed to manipulate the array will go where the “do this stuff” code block is. There we could print, search, or create many other possible implementations. Also and as you know, the code block is usually written on separate lines.

Here’s a sample loop to print all items to the screen:

Fig 11

On line 2 the console.log() is addressing each array location. We accomplish this by assigning i as the number for the location. In this way, as the loop counts the i numbers, it changes the position of the y[i] and each items is displayed accordingly (and in separate lines). Let’s try it next.