Introduction to JavaScript Variables and Arrays

Mon, Sep 19, 2016


JavaScript is a coding language used in webpages. It enables you to do things like add interactivity to a website, build applications, and retrieve data from other sites.

This tutorial is used as a reference guide to a class taught at the UC Berkeley Graduate School of Journalism on coding for journalists. It is recommended that this tutorial be used as a complement to a course on JavaScript and/or coding fundamentals. Parts of a webpage:

Webpages are made up of three elements:

  1. HTML — The structure and content of the webpage.
  2. CSS — The style and design of the webpage.
  3. JavaScript — Code that enables things like interactivity or manipulation of elements on a webpage.

All three parts of a webpage are written in a unique syntax, and are considered different languages.

Where does JavaScript reside?

JavaScript is stored right inside the HTML of a webpage. The code itself is put in one of two places:

Linking to a JavaScript file

JavaScript can be stored in a separate text file that is referenced in your HTML. Generally, this separate text document has the file extension .js

JavaScript is included on a webpage using the <script> tag. To link to a javascript file, use the following syntax:

<script type="text/javascript" src="path_to_file/filename.js"></script>

It is important to note that when linking to JavaScript files, you need both an opening and closing <script> tag.

Inline JavaScript

JavaScript can also be written directly within the HTML of a webpage, also using the <script> tag. Put your code between the opening and closing script tags.

<script type="text/javascript">
    //JavaScript code here

The attribute type="text/javascript" is not required, but some believe it is good practice to use it. A plain <script> tag will also work, as all modern browsers automatically default to JavaScript language when the see a <script> tag with no attribute.


JavaScript is a lot like math in the sense that we store data in variables. Here is some info about variables, and how they work in JavaScript.

Variables in JavaScript must follow a certain set of naming rules.

  • Variables should start with a letter (underscore or dollar symbol are also acceptable, but typically reserved for certain situations)
  • Variables can only contain letters, numbers, an underscore, dollar symbol, or Unicode characters
  • Variables cannot have spaces
  • Variables in JavaScript are case sensitive, which means the variable mytotal is a different variable than myTotal.

Variable names can be a single letter, such as i, j or k. But it is better better to use more descriptive names such as total, sum or totalscore. You will come up with your own names for variables in your program which pertain to your own application.

Semicolon (;)

A semicolon terminates a line of code. Think of it similar to a period at the end of a sentence. Technically, semicolons are optional in JavaScript, but considered good practice.

The VAR keyword

When using variables in JavaScript, you should declare them using the VAR keyword. This establishes the word you picked to be used as a variable under a certain “scope,” or place. (more on what this means in the section on functions.)

var i;
var total;
var numberofphotos;

Only use the var keyword the first time you mention a variable in any scope (space).

Assignment Operator

The expression:

var x = 7;

means that we are storing the value 7 inside the variable x. It does not establish equivalency — saying x is the same as 7 — rather, the equals sign is performing a task of storing the value on the right inside the variable on the left.

Assignment process in JavaScript

It is also possible to replace the value of variable with something else. Thus the expression:

var x = 7;
x = 8;
x = 9;

means that x will be 9 — the final value. Each time we assign a new value, it replaces the old value.

Assignting a Variable to Another Variable

When a variable is assigned to another variable, it receives its value, as in this example:

var x = 8;
var y = x;

The value of y is 8. Because in the first line, we assigned 8 to the x variable. Then in the second line, we assigned the value of x, to y.

Basic Math Operations

In JavaScript, you can perform some basic arithmetic operations.

var x = 5 + 7;

The value of x will be 12. Likewise, you can use other variables for a part of these math operations.

var x = 5;
var y = 2;
var j = x + y;

In this case the value of j will be 7. You can also perform multiplcation and division, and even use parethesis much the same way you do with algebraic expressions. Multiplication is done with an asterisk (*), and division with a forward slash (/).

var x = 9;
var y = (x / 4) * (x + 3);

The value of y is 27, or 9 divided by 4, multiplied by the sum of 9 and 3.

String Data Type

Variables can store more than numbers. They can also store words, phrases and several other types of abstract data. If you want to store a word or a phrase, you need to surround it by quotes. (both single or double quotes work.)

var myname = "Jeremy";
var website = "Knight Digital Media Center";

If you don’t use quotes, the browser will think you are trying assign values to another variable.


What happens with you try add two string variables? In JavaScript, it simply connects the two together in a process called concatenation.

firstname = "Jeremy";
lastname = "Rue";
fullname = firstname + lastname;

In the above example the value of fullname is JeremyRue. Notice there is no space. That is becauase JavaScript will concatenate variable exactly without the addition of spaces. Notice the following example:

sentence = "This tutorial is written by";
firstname = "Jeremy";
lastname = "Rue";
fullsentence = sentence + " " + firstname + " " + lastname;

In this example, the fullsentence variable will contain the string This tutorial is writtten by Jeremy Rue, with spaces between all words.

Concatenating strings with numbers

It is also possible to concatenate strings and number. The result will always be a string.

firstnumber = "4";
secondnumber = 5;
fullnumber = firstnumber + secondnumber;

In this example, the value of fullnumber would be the string “45.” It’s important to understand when variables are numbers, and when they are strings of text that simply contain numbers. Taking the example above, if we didn’t have quotes around the 4, it would not concatenate the two values, but rather combine them.

firstnumber = 4;
secondnumber = 5;
fullnumber = firstnumber + secondnumber;

In this example, the value of fullnumber is 9. Because the type of data in both of these variables are numbers, they are not concatenated, but rather combined as numbers.

Boolean Data Type

Variables in JavaScript can store much more than numbers and text strings. They can also store a wide array of abstract data types. One of these is the Boolean data type, which only has two values: true and false. Why we would want to store a true or false value in a variable doesn’t make a lot of sense right now. But later, in the section on conditionals, it becomes a vital tool.

var showtooltip = false;

Assigning a Variable to Itself

Sometimes you want to change the value of a variable, based on its current value. This often done by assigning a variable to itself, and applying the changes.

var x = 27;
x = x + 3;

In the above example, the value of x is now 30. When you assign a variable to itself, the value doesn’t change until the operation is complete. It is also possible to do this with strings, which concatenates the variable:

var fullname = "Jeremy";
fullname = fullname + " " + "Rue";

In the above example, the value of full name is Jeremy Rue. We first assign it the value Jeremy, then we assign the original value with the last name concatenated.


An array is a method of storing multiple values in a single variable.

var myarray = ["bob", "john", "peter", "sandy"];

Each value in an array is separated by a comma. The values can also have a unique data types. For example, some values can be numbers, while other values can be strings or booleans.

var myarray = ["joe", 47, false, true];

In order to retrieve any element in the array, we use something called the index number. It is important to note that the index of every array starts on zero.

var myarray = ["bob", "john", "peter", "sandy"];
console.log( myarray[2] );

In the above example, myarray[2] would retrieve the value “peter” because it is the third element in the array. (remember, we start on zero.) We can also cite the index in a number of ways. What are the values of the following variables?

var myarray = [
var x = 1;

myarray[1 + 2]

In the first example, myarray[1+2] would retrieve the “sandy” value, because it is the fourth element. In the second example, the myarray[x] would retrieve the “john” value, because it is the second element. This idea of being able to bring up a value becomes very useful later, especially when working with large datasets.

It’s also important to note how the array was typed out on multiple lines. JavaScript doesn’t care how the information is presented, as long as the opening and closing brackets match up correctly. Changing Values Within an Array

You can change individual values within an array by referencing them by their index number. Consider the following:

var myarray = [

myarray[1] = "mary";

The john value no longer exists in myarray, because we’ve replaced it with mary. Remember, john was located at index 1, which is the second value because indices start on zero.

Multidimensional Arrays

A multidimensional array sounds more complicated than it is. The idea is simple: An array within an array. Sometimes the key to grasping a multidimensional array lies in how it’s typed out.

var my2Darray = [
    ["bob", "alex", "joe", "wendy"],
    ["teresa", "jodi", "sara", "peter"],
    ["jack", 44, 90],
    [true, false]

The above array has four elements, each one is also an array. So how do we reference each item? We use indexes for both the main array, and each child array nested. For the above array:

my2Darray[0][1] //This would return "alex"
my2Darray[2][2] //This would return 90
my2Darray[3][0] //This would return true
my2Darray[2][3] //This is undefined, since there is no fourth element

We used the name 2D array because this is a two-dimensional array. It is possible to further have more arrays nested within these arrays, and so on. It begins to get very complex however. Generally, most arrays don’t go too far beyond three dimensions. More ways to write arrays

Arrays can be typed and declared in a number of ways. If you want to declare a variable as an array without assigning any values to it, you have to use a special statement called a constructor. Here are two ways to do this:

var myarray = new Array();
var myarray = [];

These are both functionally the same thing. Once you’ve declared your array, it is possible to change out or assign specific values at various indices.

var myarray = [];
myarray[3] = "john";
myarray[2] = 56;
myarray[102] = "Peter";

If there was already a value in those spots, it would be replaced.

When you reference an array item, it works just like any other variable. You can concatenate them, or use them in arithmetic functions, like so:

var myarray = [1, 2, 3, 4, 5, 6, 7];
var sum = myarray[2] + myarray[4];

The value of sum would be 8, since we are adding the values 3 and 5. Remember, indices start on zero.

Test yourself:

var myarray = ["Java", "learned", "I", "today", "Script"];
var indices = [3, 2, 1, 0, 4];

//What is the value of the variable message?

var message = myarray[indices[0]] + " " + 
     myarray[indices[1]] + " " + 
     myarray[indices[2]] + " " + 
     myarray[indices[3]] + myarray[indices[4]];

In the above example, we actually use an array to represent the index value of each array.