CommonLounge Archive

JavaScript: Variables, Arrays and Objects

September 26, 2018

In the last tutorial, you learnt about the basics of numbers and strings in JavaScript. In this tutorial, you’ll learn about variables, arrays and objects. Let’s get started!

Variables

An important concept in programming is variables. Variables are used to store values.

The word ’variable’ means ’can change’. It is used because variables can store many different types of values and can change their value many times.

A good analogy for the variable is a box. You can imagine the name of the variable as the label on the box, and the value of the variable as what’s stored inside it.


Creating a variable in programming terms is called declaring a variable. Let’s declare our first variable!

var x = "My first variable!";

var is shorthand for variable. You should read the above statement as “Assign the value “My first variable!” to a (new) variable named x.”

So how do we know what value is actually stored in the variable? Simply write a console.log statement as usual:

var a = "My first variable!";
console.log(a);

Output:

My first variable!

Yippee! Your first variable! :)

Of course, variables can be anything — numbers too! Try this:

var n = 4;
var s = "Hello";
console.log(s.repeat(n));

Output:

HelloHelloHelloHello

Remember we said all expressions in JavaScript evaluate to a single value? The result of evaluating a variable is simply the value stored inside it. So, the step-by-step breakdown of evaluating the above expression would be:

> s.repeat(n) 
> "Hello".repeat(n)  <—- JavaScript looks up the value stored in variable "s"
> "Hello".repeat(4)  <—- JavaScript looks up the value stored in variable "n"
> "HelloHelloHelloHello"

You can always change the value stored in a variable:

var s = "Commonlounge";
console.log(s);
s = 12842;
console.log(s);

Output:

Commonlounge
12842

You don’t need to put var before the variable name everytime you change its value. It’s no longer required once you’ve declared the variable. In fact, it’s not even necessary to use it while declaring a variable. But, it’s a good practice to do so to make it clear when you are declaring new variables vs re-using an existing one. There’s another reason to do this related to variable scope, which you will learn about later in this course.

When you store a new value in a variable, the old value gets tossed out. This means we can’t get back to "Commonlounge" again, unless we stored it in some other variable. For example:

var x = "Commonlounge";
var y = x;
console.log(y);
x = "David";
console.log(x);
console.log(y);

Output:

Commonlounge
David
Commonlounge

Above, when we did var y = x, y now has the value "Commonlounge" inside it. Then we updated the value of x to "David", but y is unchanged.

You can also use a variable to assign value to itself.

var name = "Commonlounge";
name = "Hello " + name + "!";
console.log(name);

Output:

Hello Commonlounge!

When you do name = "Hello " + name + "!", you are asking JavaScript to evaluate the expression "Hello " + name + "!", and store the result in name.

Here’s another example:

var a = 5;
a = a * 3;
console.log(a);
a = a * a;
console.log(a);

Output:

15
225

Awesome, right?

But, what if we used the wrong name? Can you guess what would happen?

var website = "https://www.commonlounge.com";
console.log(webcite.length);

Output

< Uncaught ReferenceError: webcite is not defined
    at <anonymous>:1:1

We get an error called ReferenceError. It means that the variable name that we are referring to, has not been defined yet. If you encounter this error later, check your code to see if you’ve mistyped any names.

Arrays

Beside strings and integers, JavaScript has all sorts of different types of objects. Now we’re going to introduce one called Array. An array is just a list of values.

Creating an Array

There are two different ways to create an array - new Array() or []:

console.log(new Array());
console.log([]);

Output:

[]
[]

Note: Please note that the output from the “Try it now” code block may be formatted slightly differently from the “Output” we show above. For instance, you may have noticed empty output instead of [] for an empty array. This is totally okay! You may, in fact, different see slightly differently formatted outputs for arrays in different browsers.

You can use either of the above to create an empty array.

You can specify the number of elements in the array by using the new Array() method.

console.log(new Array(0));
console.log(new Array(100));

Output:

[]
(100) [empty × 100]

The console returns two things: the first number in parentheses, is the length of the array and it is followed by the contents of the array.

Yes, this array is empty. Not very useful, right?


Let’s create an array of some ball games. We don’t want to repeat ourselves all the time, so we will put it in a variable, too:

var ballgames = ['basketball', 'tennis', 'cricket', 'football', 'baseball'];
console.log(ballgames);

Output:

["basketball", "tennis", "cricket", "football", "baseball"]

All right, we have an array!

Accessing array elements

If you want to access the first number, you can do this by using indices. An index is the number that says where in an array an item occurs. Programmers prefer to start counting at 0, so the first element in your array is at index 0, the next one is at 1, and so on. Try this:

var ballgames = ['basketball', 'tennis', 'cricket', 'football', 'baseball'];
console.log(ballgames[0]);
console.log(ballgames[2]);

Output:

basketball
cricket

As you can see, you can access different elements in your array by using the array’s name and the element’s index inside of square brackets.

What happens if you provide an index which is out of bounds?

var ballgames = ['basketball', 'tennis', 'cricket', 'football', 'baseball'];
console.log(ballgames[-1]);
console.log(ballgames[100]);

Output:

undefined
undefined

JavaScript just returns undefined.

Modifying / Updating Arrays

Updating a value inside the array is quite straightforward:

var ballgames = ['basketball', 'tennis', 'cricket', 'football', 'baseball'];
ballgames[2] = "volleyball";
console.log(ballgames);
ballgames[2] = "cricket";
console.log(ballgames);

Output:

["basketball", "tennis", "volleyball", "football", "baseball"]
["basketball", "tennis", "cricket", "football", "baseball"]

You can use the .push(item) and .pop() functions to add an element to an array and remove the last element from an array, respectively.

var ballgames = ['basketball', 'tennis', 'cricket', 'football', 'baseball'];
ballgames.push("volleyball");
console.log(ballgames);
ballgames.pop();
console.log(ballgames);

Output:

["basketball", "tennis", "cricket", "football", "baseball", "volleyball"]
["basketball", "tennis", "cricket", "football", "baseball"]

Playing with Arrays

What else can we do with it arrays? Let’s see how many values there are in the array. Can you guess which attribute you should use for that? You know this already!

var ballgames = ['basketball', 'tennis', 'cricket', 'football', 'baseball'];
console.log(ballgames.length);

Output:

5

Yes! ballgames.length can give you a number of objects in the array. Handy, right? Maybe we will sort it now:

var ballgames = ['basketball', 'tennis', 'cricket', 'football', 'baseball'];
console.log(ballgames.sort());

Output:

["baseball", "basketball", "cricket", "football", "tennis"]

Maybe we want to reverse that order? Let’s do that!

var ballgames = ["baseball", "basketball", "cricket", "football", "tennis"];
console.log(ballgames.reverse());

Output:

["tennis", "football", "cricket", "basketball", "baseball"]

Note that both sort and reverse modify the array ballgames.

We can also concatenate two arrays.

var ballgames = ["tennis", "football", "cricket", "basketball", "baseball"];
var othergames = ["archery", "boxing"];
console.log(ballgames.concat(othergames));
console.log(ballgames);

Output:

["tennis", "football", "cricket", "basketball", "baseball", "archery", "boxing"]
["tennis", "football", "cricket", "basketball", "baseball"]

The first line shows the concatenated array. As we can see from the second line, it doesn’t store changes. Notice the difference between concat vs sort or reverse.

How do we store the concatenated array in a new array called games?

var ballgames = ["tennis", "football", "cricket", "basketball", "baseball"];
var othergames = ["archery", "boxing"];
var games = ballgames.concat(othergames);
console.log(games);
console.log(ballgames);

Output:

["tennis", "football", "cricket", "basketball", "baseball", "archery", "boxing"]
["tennis", "football", "cricket", "basketball", "baseball"]

Now let’s say you want to a string with the values in ballgames separated by a space.

var ballgames = ["tennis", "football", "cricket", "basketball", "baseball"];
console.log(ballgames.join(" "))
console.log(ballgames);

Output:

tennis football cricket basketball baseball
["tennis", "football", "cricket", "basketball", "baseball"]

.join(<separator>) joins the items inside the array separated by the parameter passed to it.

Everything we described above works for JavaScript arrays with numeric values, with the exception of .sort(). JavaScript can sort arrays with string values easily. But for numbers we need to do something more. The .sort() function takes as a parameter, a comparison function, which is used to do compare two values and decide which one is smaller. For strings, JavaScript has a pre-defined comparison function which sorts them alphabetically. For numbers we need to define our own comparison function. You’ll learn about creating your own functions later in this course.

JavaScript Objects as Dictionaries / Maps

Dictionaries are similar to arrays, but you access values by looking up a key instead of a numerical index. A key can be any string or number.

Creating an Object

The syntax to define an empty object is:

var emptyObject = {};

Before we play with Dictionaries more, here’s a quick aside. To print dictionaries, we will have to convert them to a string using a special JSON.stringify() function. We will look at this in more detail later, but for now, think of this as a function that can magically make your dictionaries suitable for printing. See the example below.

Now, try writing the following (try substituting your own information, too):

var participant = {
    'name': 'Commonlounge', 
    'country': 'Canada', 
    'favorite_numbers': [7, 42, 92]
};
console.log(JSON.stringify(participant));

Output:

{
    'name': 'Commonlounge', 
    'country': 'Canada', 
    'favorite_numbers': [7, 42, 92]
}

With this command, you just created a variable named participant with three key–value pairs:

  • The key 'name' points to the value 'Commonlounge' (a string object),
  • 'country' points to 'Canada' (another string),
  • and 'favorite_numbers' points to [7, 42, 92] (an array with three numbers in it).

Accessing elements

You can access the content of individual keys in the following ways:

var participant = {
    'name': 'Commonlounge', 
    'country': 'Canada', 
    'favorite_numbers': [7, 42, 92]
};
console.log(participant['name']);
console.log(participant.name);

Output;

Commonlounge
Commonlounge

See, an object is similar to an array. But you don’t need to remember the index – just the name.

Both of the above listed ways work. In this tutorial, we will use participant['name'] syntax, and this is the preferred syntax to use. But in general, either syntax works.

What happens if we ask JavaScript the value of a key that doesn’t exist? Can you guess? Let’s try it and see!

var participant = {
    'name': 'Commonlounge', 
    'country': 'Canada', 
    'favorite_numbers': [7, 42, 92]
};
console.log(participant["invalid_key"]);

Output:

undefined

JavaScript just returns undefined if the key is invalid.

When should you use an object instead of an array?

When should you use an object or an array? Well, that’s a good point to ponder. Just have a solution in mind before looking at the answer in the next line.

  • Do you just need an ordered sequence of items? Go for an array.
  • Do you need to associate values with keys, so you can look them up efficiently (by key) later on? Use an object.

Modifying / updating objects

Objects, like arrays, are mutable, meaning that they can be changed after they are created. You can add new key–value pairs to an object after it is created, like this:

var participant = {
    'name': 'Commonlounge', 
    'country': 'Canada', 
    'favorite_numbers': [7, 42, 92]
};
participant['favorite_language'] = 'JavaScript';
console.log(JSON.stringify(participant));

Output:

{name: "Commonlounge", country: "Canada", favorite_numbers: Array(3), favorite_language: "JavaScript"}

You can use the delete command to delete an item in the object. Say, if you want to delete the entry corresponding to the key 'favorite_numbers', just type in the following command:

var participant = {
    'name': 'Commonlounge', 
    'country': 'Canada', 
    'favorite_numbers': [7, 42, 92]
};
delete participant['favorite_numbers'];
console.log(participant['favorite_numbers']);
console.log(JSON.stringify(participant));

Output:

undefined
{name: "Commonlounge", country: "Canada"}

As you can see from the output, the key–value pair corresponding to the favorite_numbers key has been deleted.

You can also change a value associated with an already-created key in the object. Try this:

var participant = {
    'name': 'Commonlounge', 
    'country': 'Canada'
};
participant['country'] = 'Germany';
console.log(JSON.stringify(participant));

Output:

{name: "Commonlounge", country: "Germany"}

Objects vs Dictionaries

In many programming languages, dictionaries and Objects are two separate things. In JavaScript, Objects are directly used to implement dictionaries as described above. However, this also means that (a) you can do more with JavaScript Objects than we have described so far - you’ll learn about JavaScript Objects used as full-fledged Objects later in the course. We have described how JavaScript dictionaries functionality is achieved in JavaScript using Objects, and (b) some things that should be easy to do with dictionaries is not so easy to do in JavaScript. For example, finding out the number of key-value pairs in the dictionary, or finding the list of all keys in the dictionary.

Summary

Awesome! You know a lot about programming now. In this last part you learned about:

  • variables – names for values that allow you to code more easily and to make your code more readable
  • arrays – collections of values stored in a particular order
  • objects as dictionaries – items stored as key–value pairs

Excited for the next part? :)


© 2016-2022. All rights reserved.