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

JavaScript in Plain Language (2015)


2.14 Unordered lists

· We have seen how the numeric data structure of type array stores data in its ‘pockets’. The first item goes on pocket zero, the second item on pocket 1, the third item goes on pocket 2, etc.

· The location of the last item of an array is always the length of the array minus 1. Do not memorize this fact, just understand that locations start counting from zero. This is great to know if we ever need to manually add an item to the array. As for automatically adding new items, we may use push() to insert them at the end, or unshift() to place them at the beginning, or if we want to insert an item in a specific location we can use splice(). On the other hand, to delete items we use pop() if the item is at the end, shift() if at the beginning, and the versatile splice() if we want to delete an item from a specific location.

· As for scanning arrays, we traverse the array with a for loop in order to print its contents, and we also know that the JavaScript library has many other methods we can use for further manipulating arrays. Some of these methods were covered in this book, and the other more advanced methods may be read on my “explained” eBook.

In this topic we are going to work with unordered lists.

In unordered lists all item locations are labeled with a string value.

We call them unordered lists because each pocket is literally labeled. This label can be a single character, or a word, or even a number (however if you use numbers as labels, know that they are not sequential and they are treated as characters as opposed to arrays which are always numerically sequential).

In truth, the unordered list is unordered because JavaScript maps the label to the item. In the end, these are all arrays, even if such characteristic becomes hidden from the programmer.

In an official array we don’t have to name the address or pocket label because it is numerically assumed, like for example:

var myArray = ["duck", "lettuce", "sapphire"];

For unordered lists we need to label the location of the item, I mean the pocket where the item is stored. That can be advantageous for certain applications:

var x = {"animal": "duck", "vegetable": "lettuce", "mineral": "sapphire"};

Notice how the assignment to each item is made like: "animal": "duck",

"animal" is the label and "duck" is the value.

There is a colon : separating the two, rather than an =.

We use the curly braces to wrap the list, as opposed to the square braces which are reserved to arrays.

· Please note: The quotes wrapping the label are optional, but not the quotes wrapping the string value, those are mandatory because in our example we are using string values.
More about that later.

Hashes, objects, associative arrays, unordered lists

In JavaScript all these names are synonymous. Each programming language uses a different terminology to represent unordered lists.

Java uses HashMap, HashTable.

C# uses HashTable, Dictionary.

Python uses dict.

Ruby uses Hash.

Object-c uses NSDictionary.

C++ uses std::unordered_map.

And JavaScript uses object.

Did I just say object? Personally I don’t like the name designation because, in JavaScript, almost everything is an object. Arrays are also objects, and so are functions. However, the name of object in JavaScript has become synonymous with unordered lists.

Another popular name is associative arrays. Some languages actually have associative arrays. In JavaScript an associative array which is an array with key-value pair association, is called an object. However the reason why an associative array is often called an object is because objects in the sense of the term are made with associative arrays. As far as JavaScript is concerned, all these names are unordered lists and we call them objects.

Hopefully this clears up some of the confusion by knowing that they all mean the same thing, but please keep in mind that things are not that simple, there is a lot more to this subject than what this book calls for.

· From now on and for simplicity’s sake, we are going to call any key-value pair structure an object.

Creating an object

An object is a collection of values.

These values can be a mix of anything: strings, numbers, Boolean expressions, variables, arrays, functions and (often) other similar objects.

JavaScript is very versatile in that aspect. The size of a list of values can shrink or expand at any time. We will see how to do all these, like creating, editing, adding new items, deleting items, searching and printing items in the next few pages. Most of these techniques have already been introduced to you and you will remember them as we approach each one of them.

Declaring an object and assigning values at the same time:

var x = {"animal": "duck", "vegetable": "lettuce", "mineral": "sapphire"};

What do we have above?

We have a variable named x that points to a data structure of type object. We know it is an object because of the curly braces wrapping the data: { }.

The variable x and the data structure in itself are in separate (and different) parts of the memory. They are independent of each other. This memory independence also happens for arrays and functions, but there is no separation of variable name and value when we declare a simple string or anumeric variable; those reside on the same location as the variable name. We will cover a bit more about it later.

So now we have an object assigned to variable x.

Since the data structure is divided into key-value pairs we can address the values by calling the corresponding keys. Think of the key as the label for the value.

Instead of x[0]; we now can ( and must) do it this way:


It displays "duck". By the way, when using bracket notation, the quotes wrapping the label are mandatory. Notice how "animal" is wrapped in quotes. Labels are strings values. Now if you ever use a number as a key (and you can do it), you may also wrap it in quotes or you may not. JavaScript allows numbers to be written in both styles on bracket notation (but numbers are rarely used as labels).

Why should we wrap key labels in double quotes?

Normally, when we create an object we don’t really have to wrap the key portion of a property in quotes and you may see it more often that way (no quotes). Example:

var example = {animal: "duck", vegetable: "lettuce"};

As you see, there are no quotes for animal and for vegetable in the object declaration.

However, wrapping key labels with double quotes is being used more and more in modern technology, thanks to the advent of JSON which is being applied everywhere. We will cover the basics of JSON on a later chapter.

So if you are beginning to learn object notation, you might as well develop the habit of double quoting keys when you declare an object.

The above example should then look like the following:

var example = {"animal": "duck", "vegetable": "lettuce"};

Do it as you wish but please keep this concept in mind.

Assigning new key-value pairs to objects

Let’s do some lab work...

1- On your Console, create a new and empty object:
var crazyList = { };

Do you still remember how to check the type of a variable with typeof (covered on Lab work 1)?

2- Let’s check the typeof crazyList:
typeof crazyList;

It displays "object". We have an empty object.

3- Now we add some values by assigning them to key labels:
crazyList["flower"] = "daisy";

Object crazyList now contains {flower: "daisy"}

4- Let’s add another key-value pair:
crazyList["drink"] = "water";

crazyList now has two values:
{flower: "daisy", drink: "water"}

As a curiosity, notice how JavaScript is placing the new items to the right of the last item. However, it doesn’t really matter where the items are being placed since, unlike arrays, we don’t need such information in order to access those items.

5- Now we’re going to add some numeric keys just to see what happens
(not a common implementation):
crazyList[2] = "front teeth";

crazyList is now holding 3 items:
{2: "front teeth", flower: "daisy", drink: "water"}

Do you see how the numeric key was placed to the left of all the string type keys?
Again, this has no meaning to us because it is not really consistent.

6- Let’s add two other numeric keys:
crazyList["1"] = "flying bird";

crazyList[3] = "is a crowd";

Now crazyList contains:
{1: "flying bird", 2: "front teeth", 3: "is a crowd", flower: "daisy", drink: "water"}

So we see that when the key is numeric, the item is placed on the left side and also in numeric sequence. When the key is a string value, the item is placed after the last rightmost item.

Also notice how I wrapped ["1"] in quotes. That was just to show that, when it comes to numeric keys, they can be wrapped or not. It is up to you.

· The sequential positioning of key-value pairs has no value for us at this moment. It was just mentioned as a curiosity. Please don’t try to memorize such characteristic since this is an unordered list and we will pick items by calling their labels at will.

Using dot notation with objects

On the previous example we had used bracket notation to call the labels that correspond to each object property (the value).

We can also use dot notation to represent object properties.

This is actually a very popular way to address items of an object. In truth, we need to become very familiar with both styles of writing because, as much as dot notation is popular, sometimes it cannot be used. On the other hand, if you only use bracket notation your code will look different than the norm and someone will ask you why such style of writing. It is worth learning how to write certain expressions in dot notation and others in bracket notation. Practice will tell you which one to use and when.

Here’s what you should know about the differences between these two styles of coding:

1. Dot notation will not work with numbers.

2. Dot notation will not work with dynamic variables (those that change dynamically such as a counter representing a key in a key-value pair when traversing an object with a loop).

3. In summary, dot notation can only be used when the property name is a valid identifier of a property and as long as this identifier is not numeric.

Think of dot notation as hardwired (the value must be known when dot notation is used), and bracket notation as soft wired (the value can dynamically change or be unknown at the time the code is presented to the JavaScript interpreter).

How do we use dot notation to address an item in an object?

Let’s repeat our previous examples using dot notation instead of bracket notation:

1- Create a new and empty object:
var crazyList = { };

2- Let’s add some values by assigning them to key labels:
crazyList.flower = "daisy";

Now crazyList contains {flower: "daisy"}

Notice how in dot notation a key is written without quotes. This is because flower is already in memory as a declared key to a property in object crazyList. In bracket notation however, we always include the key string names in quotes, like "flower". In dot notation quotes are not valid.
This crazyList."flower"= would result in an error

3- Add another key-value pair:
crazyList.drink = "water";

Now crazyList contains:
{flower: "daisy", drink: "water"}

4- Add a numeric key using dot syntax:
crazyList.2 = "front teeth";

We get the following error as a result:
SyntaxError: Unexpected number

Numbers are not allowed in dot syntax. It needs to be done this way:
crazyList[2] = "front teeth";

In summary:

We can declare an empty object by assigning a pair of curly braces to a variable:

var z = { };

Then we can add items by providing a key and a value in either dot notation or bracket notation: = 750;

z["gasBill"] = 300;

And now we have {rent: 750, gasBill: 300}


We can declare an object and assign items to it all at once:

var b = {"color": "red", "fabric": "cotton"};

And now we have {color: "red", fabric: "cotton"}.

Spanning an object declaration across multiple lines

Up to this point our objects have been short and one liners. For the most part however, objects are more complex and span over several lines of code.

There is no difference between a single line object and a multiple line object. The second style of writing objects is just easier for the eye, but JavaScript does not care one way or the other.

1- Here’s an example of a multiple line syntax style. Please write the code along with me just for practicing purposes. There is also a link to a raw file below the image:

Fig 14 see raw file |

Notice the commas. Just like in a single line object, all elements are separated by a comma except the last item. If you write a comma there (after the last item) you will get an error because the JavaScript interpreter will expect another element to its right (or in this case below it).

Notice the quotes on numbers 2014 and 67,000. The reason I added quotes is because I don’t plan to do any calculations with these numbers, so I’ve decided to treat them as strings. This is optional; you could skip the quotes and make them properties of type number. As for number 9, I’ve decided to keep it as a numeric property in case I want to calculate the average rating for all the cars in the lot. This gives us two possible approaches on how to write number properties.

Also, as explained before, technologies using JSON ( JavaScript Object Notation) want the key to be in double quotes so I have placed "make", "model", "color", etc in double quotes. In this way this script becomes machine independent, sort of like when one writes in xml notation. By writing it this way we can send the data to any machine that reads JSON and it will be understood. Quotes in keys are optional. Do it as you wish.

What is a property?

A property is what we call the data elements from an object.

We could call them variables since they are not static (their values can be changed at any time), or just object elements, but in object oriented language they are called object properties.

· Object properties are the data contained in an object and they are represented by a
name: value pair, also known as a key: value pair.

Think of an object as the owner of its name: value pair components. These components are properties of the object, just like my car, bike and scuba equipment are my properties.

var tony = {"transportation": "car", "Computer": "desktop pc"}

An object may also own some methods.

Let’s talk about methods next.

· Don’t get wrapped into this terminology trying to memorize what is called what. That will slow you down. Just move along and let your brain assimilate these terms based on practicing, not based on memorization.

What is a method?

A method is a property that executes an action on behalf of the object. If the property is not a “thing” but an action waiting to be called upon, then it is a method.

Take for example a desktop computer as an object; we could say that the display, the keyboard and the mouse are some of the properties of the desktop computer. Then we could also say that Firefox and Chrome browsers, as well as Microsoft Word are methods of the desktop computer because these properties have functionality, they don’t exist in the physical sense, we need to call them like we call a function, in order to use them. They represent some of the methods of a desktop computer. Their existence is based on the execution of some program routine.

When we mention “execution” we immediately thing of functions, but there is a difference between what a function is and what a method is:

· A method may contain one or more functions.

Do you see the difference? A function could be a method of an object, but it is not necessarily a method in itself. A method is a collection of functionality to accomplish a task on behalf of an object. Like a method to print out a list of contents, or a method to update the contents of an object, or a method to sort the contents, or a method to identify the person asking for the contents of an object, and so on.

Let’s add a method to our car object.

2- If you’ve been coding along with me, add a new comma to rating: 9, because we are about to add one more property, the method printRating. (use the editor).

3- Assign to label printRating a function that prints on screen the following message:
"The car rates " + car.rating + " out of 10"

Fig 15 see raw file. |

4- Let’s play with this object a bit. Paste the object script from this last raw file (or your own script) on the Console.

5- Print the car’s rating:

Notice how we call() a method from an object. It starts like when we call any other property but then we add a pair of parentheses ( ) which creates a function action. What would happen if we excluded the parentheses? It would just print the contents of key printRating which are the explicit description of the function. That can be handy sometimes when we want to assign the same functionality to another variable, but in order to get an action we need to use the parentheses.

6- What about bracket notation? How would we call the method printRating using bracket notation? Methods are best called with dot notation because it is an easier syntax as you will see why next, but it is good to understand how the logic goes and here it is:

Not as pretty as in dot syntax, right? Notice how the parentheses go outside of the brackets. So this is one area where dot syntax is mostly used. Bracket syntax is reserved more for the dynamic calling of a property. We use bracket syntax with for loops because there, each property needs to be accessed dynamically as the loop goes around.

Let’s do that!

Looping through an object

Suppose you are aware of an object existence but you don’t really know what properties it contains.

You can loop through the object to find its properties.

Introducing the for in loop

This loop is written specifically for the object we’ve been discussing:
See original file here: raw file |

The loop goes like this:

for(var k in car){

The for in loop is a variation of the regular for loop in the sense that some functionality is already preprogrammed in the JavaScript library. Let’s explore it line by line:

for(var k in car) --- k is a variable introduced by the programmer. Its purpose is to temporarily grab and hold the key label for each loop count (the label that matches the location number in each loop cycle).

Let me explain: objects are in a sense just like arrays. The only difference is how the keys are mapped. In arrays, JavaScript maps each location as location 0,1,2, 3, etc. But in unordered lists or objects where keys are being used, JavaScript maps the internal location (whatever location it is) to the key that was originally declared for any given data value.

So, the purpose of variable k is to count each location (one per cycle) and at the same time, to grab the key name that corresponds to the given count, so that we can get to the data value assigned to it. It’s not k that does all these. It is JavaScript that provides such information and stores it in k.

As for the name k, we could use any name, such as for example i but k makes more sense because in fact, JavaScript will temporarily store the key values on variable k, one key per loop iteration. So the letter k reminds us of what is being stored there, a temporary location instance. You may also see it on the field or in other texts as key, prop, or property.

(Why am I telling you all this? because I don’t want you to start reading posts on the web and think that there are a thousand different kinds of for in loops. There is only one for in loop and each developer gets creative with temporary variable names).

Going back to our “for k in car”, in this example we have a dedicated for in loop because we know the name of the object, car. We could however make this loop generic and substitute car with another temporary variable to act as a placeholder, like for example a parameter from a function. Then we could insert the real object name as an argument when we call the function, and the function would substitute the placeholder with the correct object name. We will try that on another exercise.

console.log(k) --- This line is used to print all key names as they are passed to variable k. If however, we wanted to print the values instead of the keys, we need to address each key-value pair dynamically using bracket syntax:


JavaScript evaluates car[k] and replaces it with the value of the property corresponding to the dynamic label instance in k.

· Notice the lack of quotes on "k". k is a declared variable.Variables never take quotes because that will make them a string and JavaScript will think it is a different identifier other than the one we intend to target. k is a variable, "make" or "color" are not variables, they are real keys and a key is a string. Those would be wrapped in quotes if used in bracket notation: car["color"].

Also, remember that dot notation will not work here. This is because the loop is dynamically addressing the key values by mapping k to the key, and dot notation only accepts the real key name. Remember: hard wire versus soft wire.

1- So let’s paste the object on the Console, then paste the for in loop just to print the key names

· Here’s the complete raw file |

You should see the following keys displayed:

2- Replace (k); with (car[k]); on your console log. Remember, you can move up in the Console by click on the Up Arrow, then modify the script and press ENTER.

Now the printout should look like this:

And the printout should be:
function () {
console.log("The car rates " + car.rating + " out of 10");

Of course we could have made it prettier by adding the key, like for example in this way:
console.log(k + ": " + car[k]);

And that would give us:
make: Subaru
model: Outback
color: blue
year: 2014
mileage: 67,000
rating: 9
printRating: function () {
console.log("The car rates " + car.rating + " out of 10");

NOTE: I will show how to exclude the printRating method from the printout in a future exercise.

In case you’re wondering about it, I don’t really know the rating for an Outback, the number 9 is just for practicing purposes only.