facebook google plus twitter
Webucator's Free JavaScript Tutorial

Lesson: Variables, Arrays, and Operators

Welcome to our free JavaScript tutorial. This tutorial is based on Webucator's Introduction to JavaScript Training course.

In this lesson, you will learn about variables, arrays, and operators.

Lesson Goals

  • Learn to create, read and modify JavaScript variables.
  • Learn to work with JavaScript arrays.
  • Learn to work with JavaScript operators.

JavaScript Variables

Variables are used to hold data in memory. JavaScript variables are declared with the var keyword.

var age;

Multiple variables can be declared in a single step.

var age, height, weight, gender;

After a variable is declared, it can be assigned a value.

age = 34;

Variable declaration and assignment can be done in a single step.

var age = 34;

A Loosely Typed Language

JavaScript is a loosely typed language. This means that you do not specify the data type of a variable when declaring it. It also means that a single variable can hold different data types at different times and that JavaScript can change the variable type on the fly. (This "casual" approach to typing can lead to difficulties in writing and maintaining large applications - tools like TypeScript offer a solution to this challenge.)

For example, the age variable above is an integer. However, the variable strAge below would be a string (text) because of the quotes.

var strAge = "34";

If you were to try to do a math function on strAge (e.g., multiply it by 4), JavaScript would dynamically change it to an integer. Although this is very convenient, it can also cause unexpected results, so be careful.

Variable Naming

  1. Variable names must begin with a letter, underscore (_), or dollar sign ($).
  2. Variable names cannot contain spaces or special characters (other than the underscore and dollar sign).
  3. Variable names can contain numbers (but not as the first character).
  4. Variable names are case sensitive.
  5. You cannot use keywords (e.g., window or function) as a variable name.

Storing User-Entered Data

The following example uses the prompt() method of the window object to collect user input. The value entered by the user is then assigned to a variable, which is accessed when the user clicks on one of the span elements.

Code Sample:

VariablesArraysOperators/Demos/Variables.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript Variables</title>
<link href="style.css" rel="stylesheet">
<script>
	//Pop up a prompt
	var userColor = window.prompt("Enter a color.", "");
</script>
</head>
<body>
<p>
	<span onclick="document.body.style.backgroundColor = 'red';">Red</span> |
	<span onclick="document.body.style.backgroundColor = 'white';">White</span> |
	<span onclick="document.body.style.backgroundColor = 'green';">Green</span> |
	<span onclick="document.body.style.backgroundColor = 'blue';">Blue</span> |
	<span onclick="document.body.style.backgroundColor = userColor;">
	<script>
		document.write(userColor);
	</script>
	</span>
</p>
</body>
</html>

Code Explanation

As the page loads, a prompt pops up asking the user to enter a color.Prompt

This is done with the prompt() method of the window object. The prompt() method is used to get input from the user. It takes two arguments:

  1. The message in the dialog box (e.g., "Enter a color.").
  2. The default value that appears in the text box. In the example above this is an empty string (e.g., "").

If the OK button is pressed, the prompt returns the value entered in the text box. If the Cancel button or the close button (the red X) is pressed, the prompt returns null. The line below assigns whatever is returned to the variable userColor.

var userColor = window.prompt("Enter a color.", "");

A script block with a call to document.write() is then used to output the color entered by the user. This output is contained within a span element, which has an onclick event handler that will be used to turn the background color of the page to the user-entered color.

<span onclick="document.body.style.backgroundColor = userColor;">
	<script type="text/javascript">
		document.write(userColor);
	</script>
</span>

Using Variables

Duration: 5 to 15 minutes.

In this exercise, you will practice using variables.

  1. Open VariablesArraysOperators/Exercises/Variables.html for editing.
  2. Below the ADD PROMPT HERE comment, write code that will prompt the user for her first name and assign the result to a variable.
  3. Add a button below the Ringo button that reads "Your Name". Add functionality so that when this button is pressed an alert pops up showing the user's first name.
  4. Test your solution in a browser.

Code Sample:

VariablesArraysOperators/Exercises/Variables.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript Variables</title>
<link href="style.css" rel="stylesheet">
<script>
	//ADD PROMPT HERE
</script>
</head>
<body>
<form>
	<input type="button" value="Paul" onclick="alert('Paul');">
	<input type="button" value="John" onclick="alert('John');">
	<input type="button" value="George" onclick="alert('George');">
	<input type="button" value="Ringo" onclick="alert('Ringo');">
	<!--ADD BUTTON HERE-->
</form>
</body>
</html>

Code Explanation

Solution:

VariablesArraysOperators/Solutions/Variables.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript Variables</title>
<link href="style.css" rel="stylesheet">
<script>
	var firstName = window.prompt("What's your name?", "");
</script>
</head>
<body>
<form>
	<input type="button" value="Paul" onclick="alert('Paul');">
	<input type="button" value="John" onclick="alert('John');">
	<input type="button" value="George" onclick="alert('George');">
	<input type="button" value="Ringo" onclick="alert('Ringo');">
	<input type="button" value="Your Name" onclick="alert(firstName);">
</form>
</body>
</html>

Constants

The most-recent ("ES6") ECMAScript standard introduced the const keyword into JavaScript. Variables declared as const:

const NUM = 1;

cannot be reassigned; that is, a later statement like NUM = 2; would fail, meaning that the value of variable NUM would remain 1; depending on how the browser you are using handles const, the later statement may either cause the code to fail or simply not assign the new value to NUM.

Please note that, as this is a relatively-recent JavaScript feature, not all browsers may yet implement it, or may implement it differently. (The useful website caniuse.com lists current browser support for this - and many other - JavaScript features; see http://caniuse.com/#feat=const for a list of how browsers handle const.)

While constants can be declared with uppercase or lowercase names, the convention is to use all-uppercase names for constants.

Let's look at a simple example:

Code Sample:

VariablesArraysOperators/Demos/Const.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript const</title>
<link href="style.css" rel="stylesheet">
</head>
<body>
<script>
	const MY_VAR = 1;
	MY_VAR = 2;
	document.write(MY_VAR);
	/*
		value "1" gets written to the screen or
		code fails at line 11, depending on browser
	*/
</script>
</body>
</html>

Code Explanation

We assign a value 1 to const variable MY_VAR. On the next line, we try to assign value 2 to MY_VAR. On modern browsers, the code gives a JavaScript error: in Firefox, for example, the code fails (with console error message "invalid assignment to const MY_VAR") and no value is written to the screen. In some older version of browsers, the second assignment statement fails silently and the value 1 is written to the screen.

Arrays

An array is a grouping of objects that can be accessed through subscripts. At its simplest, an array can be thought of as a list. In JavaScript, the first element of an array is considered to be at position zero (0), the second element at position one (1), and so on. Arrays are useful for storing related sets of data.

Arrays are declared using the new keyword.

var myarray = new Array();

It is also possible and very common to use the [] literal to declare a new Array object.

var myarray = [];

Values are assigned to arrays as follows:

myarray[0] = value1;
myarray[1] = value2;
myarray[2] = value3;

Arrays can be declared with initial values.

var myarray = new Array(value1, value2, value3);
//or, using the [] notation:
var myarray = [value1, value2, value3];

The following example is similar to the previous one, except that it prompts the user for four different colors and places each into the userColors array. It then displays the values in the userColors array in the spans and assigns them to document.body.style.backgroundColor when the user clicks on the spans.

Unlike in some languages, values in JavaScript arrays do not all have to be of the same data type.

Code Sample:

VariablesArraysOperators/Demos/Arrays.html
---- C O D E   O M I T T E D ----

<script>
	//Pop up four prompts and create an array
	var userColors = new Array();
	userColors[0] = window.prompt("Choose a color.", "");
	userColors[1] = window.prompt("Choose a color.", "");
	userColors[2] = window.prompt("Choose a color.", "");
	userColors[3] = window.prompt("Choose a color.", "");
</script>
</head>
<body>
<p>
	<span onclick="document.body.style.backgroundColor = userColors[0];">
	<script>
		document.write(userColors[0]);
	</script>
	</span> |
	<span onclick="document.body.style.backgroundColor = userColors[1];">
	<script>
		document.write(userColors[1]);
	</script>
	</span> |
	<span onclick="document.body.style.backgroundColor = userColors[2];">
	<script>
		document.write(userColors[2]);
	</script>
	</span> |
	<span onclick="document.body.style.backgroundColor = userColors[3];">
	<script>
		document.write(userColors[3]);
	</script>
	</span>
</p>
</body>
</html>

Code Explanation

As the page loads, an array called userColors is declared.

userColors = new Array();

The next four lines populate the array with user-entered values.

userColors[0] = window.prompt("Choose a color.", ""); userColors[1] = window.prompt("Choose a color.", ""); userColors[2] = window.prompt("Choose a color.", ""); userColors[3] = window.prompt("Choose a color.", "");

The body of the page contains a paragraph with four span tags, the text of which is dynamically created with values from the userColors array.

Working with Arrays

Duration: 15 to 25 minutes.

In this exercise, you will practice working with arrays.

  1. Open VariablesArraysOperators/Exercises/Arrays.html for editing.
  2. Below the comment, declare a rockStars array and populate it with four values entered by the user.
  3. Add functionality to the buttons, so that alerts pop up with values from the array when the buttons are clicked.
  4. Test your solution in a browser.

Code Sample:

VariablesArraysOperators/Exercises/Arrays.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript Arrays</title>
<link href="style.css" rel="stylesheet">
<script>
	/*
		Declare a rockStars array and populate it with 
		four values entered by the user.
	*/
</script>
</head>
<body>
<form>
	<input type="button" value="Favorite">
	<input type="button" value="Next Favorite">
	<input type="button" value="Next Favorite">
	<input type="button" value="Next Favorite">
</form>
</body>
</html>

Code Explanation

Solution:

VariablesArraysOperators/Solutions/Arrays.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript Arrays</title>
<link href="style.css" rel="stylesheet">
<script>
	var rockStars = new Array();
	rockStars[0] = window.prompt("Who is your favorite rock star?", "");
	rockStars[1] = window.prompt("And your next favorite rock star?", "");
	rockStars[2] = window.prompt("And your next favorite rock star?", "");
	rockStars[3] = window.prompt("And your next favorite rock star?", "");
</script>
</head>
<body>
<form>
	<input type="button" value="Favorite" onclick="alert(rockStars[0]);">
	<input type="button" value="Next Favorite" onclick="alert(rockStars[1]);">
	<input type="button" value="Next Favorite" onclick="alert(rockStars[2]);">
	<input type="button" value="Next Favorite" onclick="alert(rockStars[3]);">
</form>
</body>
</html>

Code Explanation

Associative Arrays

Whereas regular (or enumerated) arrays are indexed numerically, associative arrays are indexed using names as keys. The advantage of this is that the keys can be meaningful, which can make it easier to reference an element in an array. The example below illustrates how an associative array is used.

Code Sample:

VariablesArraysOperators/Demos/AssociativeArrays.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Associative Arrays</title>
<link href="style.css" rel="stylesheet">
<script>
	var beatles = [];
	beatles["singer1"] = "Paul";
	beatles["singer2"] = "John";
	beatles["guitarist"] = "George";
	beatles["drummer"] = "Ringo";
</script>
</head>
<body>
<p>
	<script>
		document.write(beatles["singer1"]);
		document.write(beatles["singer2"]);
		document.write(beatles["guitarist"]);
		document.write(beatles["drummer"]);
	</script>
</p>
</body>
</html>

Array Properties and Methods

The tables below show some of the most useful array properties and methods. All of the examples assume an array called beatles that holds "Paul", "John", "George", and "Ringo".

var beatles = ["Paul", "John", "George", "Ringo"];
Array Properties
Property Description
length Holds the number of elements in an array.
beatles.length // 4
Array Methods
Property Description
join(delimiter) Returns a delimited list of the items indexed with integers in the array. The default delimiter is a comma.
beatles.join(":") // Paul:John:George:Ringo
push() Appends an element to an array.
beatles.push("Steve")
pop() Removes the last item in an array and returns its value.
beatles.pop() // Returns "Ringo"
shift() Removes the first item in an array and returns its value.
beatles.shift() // Returns "Paul"
slice(start, end) Returns a subarray from start up to, but not including, end. If end is left out, it includes the remainder of the array. It does not change the original array.
beatles.slice(1 ,3) //Returns ["John", "George"]
splice(start, count) Removes count items from start in the array and returns the removed elements as a new array.
beatles.splice(1, 2) //Returns ["John", "George"]
sort() Sorts an array alphabetically and returns the resulting array.
beatles.sort() //Returns ["George", "John", "Paul", "Ringo"]

JavaScript Operators

Arithmetic Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (remainder)
++ Increment by one
-- Decrement by one
Assignment Operators
Operator Description
= Assignment
+= One step addition and assignment (a+=3 is the same as a=a+3)
-= One step subtraction and assignment (a-=3 is the same as a=a-3)
*= One step multiplication and assignment (a*=3 is the same as a=a*3)
/= One step division and assignment (a/=3 is the same as a=a/3)
%= One step modulus and assignment (a%=3 is the same as a=a%3)
String Operators
Operator Description
+ Concatenation
var greeting = "Hello " + firstname;
+= One step concatenation and assignment
var greeting = "Hello ";
greeting += firstname;

The following code sample shows these operators in use:

Code Sample:

VariablesArraysOperators/Demos/Operators.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript Operators</title>
<link href="style.css" rel="stylesheet">
<script>
	var userNum1 = window.prompt("Choose a number.", "");
	alert("You chose " + userNum1);
	var userNum2 = window.prompt("Choose another number.", "");
	alert("You chose " + userNum2);
	var numsAdded = userNum1 + userNum2;
	var numsSubtracted = userNum1 - userNum2;
	var numsMultiplied = userNum1 * userNum2;
	var numsDivided = userNum1 / userNum2;
	var numsModulused = userNum1 % userNum2;
</script>
</head>
<body>
<p>
	<script>
		document.write(userNum1 + " + " + userNum2 + " = ");
			document.write(numsAdded + "<br>");
		document.write(userNum1 + " - " + userNum2 + " = ");
			document.write(numsSubtracted + "<br>");
		document.write(userNum1 + " * " + userNum2 + " = ");
			document.write(numsMultiplied + "<br>");
		document.write(userNum1 + " / " + userNum2 + " = ");
			document.write(numsDivided + "<br>");
		document.write(userNum1 + " % " + userNum2 + " = ");
			document.write(numsModulused + "<br>");
	</script>
</p>
</body>
</html>

Code Explanation

The file above illustrates the use of the concatenation operator and several math operators. It also illustrates a potential problem with loosely-typed languages. This page is processed as follows:

  1. The user is prompted for a number and the result is assigned to userNum1.
  2. An alert pops up telling the user what number she entered. The concatenation operator (+) is used to combine two strings: "You chose " and the number entered by the user. Note that all user-entered data is always treated as a string of text, even if the text consists of only digits.
  3. The user is prompted for another number and the result is assigned to userNum2.
  4. Another alert pops up telling the user what number she entered.
  5. Five variables are declared and assigned values.
    var numsAdded = userNum1 + userNum2; var numsSubtracted = userNum1 - userNum2; var numsMultiplied = userNum1 * userNum2; var numsDivided = userNum1 / userNum2; var numsModulused = userNum1 % userNum2;
  6. The values the variables contain are output to the browser.Browser Output

So, 5 + 4 is 54! It is when 5 and 4 are strings, and, as stated earlier, all user-entered data is treated as a string. In the lesson on JavaScript Functions, you will learn how to convert a string to a number.

Ternary Operator
Operator Description
?: Conditional evaluation.
var evenOrOdd = (number % 2 == 0) ? "even" : "odd";

The code sample below shows how the ternary operator works:

Code Sample:

VariablesArraysOperators/Demos/Ternary.html
---- C O D E   O M I T T E D ----

<script>
	var num = prompt("Enter a number.","");
	
	//without ternary
	if (num % 2 == 0) {
		alert(num + " is even.");
	} else {
		alert(num + " is odd.");
	}
	
	//with ternary
	var term = num % 2 == 0 ? "even" : "odd";
	alert(num + " is " + term);
</script>
---- C O D E   O M I T T E D ----

Code Explanation

Lines 7-11 show a regular if-else statement, which we will cover in detail in Conditionals and Loops.

Lines 14 and 15 show how to accomplish the same thing in a couple of lines of code with the ternary operator.

Default Operator
Operator Description
|| Used to assign a default value. (This is explained in greater detail later in the course.)
var yourName = prompt("Your Name?","") || "Stranger";

The code sample below shows how the default operator works:

Code Sample:

VariablesArraysOperators/Demos/Default.html
---- C O D E   O M I T T E D ----

<script>
	var yourName = prompt("Your Name?","") || "Stranger";
	
	alert("Hi " + yourName + "!");
</script>
---- C O D E   O M I T T E D ----

Code Explanation

If the user presses OK without filling out the prompt or presses Cancel, the default value "Stranger" is assigned to yourName.

Working with Operators

Duration: 15 to 25 minutes.

In this exercise, you will practice working with JavaScript operators.

  1. Open VariablesArraysOperators/Exercises/Operators.html for editing.
  2. Add code to prompt the user for the number of cds she owns of her favorite and second favorite rockstars'.
  3. In the body, let the user know how many more of her favorite rockstar's cds she has than of her second favorite rockstar's albums.
  4. Test your solution in a browser.

Code Sample:

VariablesArraysOperators/Exercises/Operators.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript Operators</title>
<link href="style.css" rel="stylesheet">
<script>
	var rockStars = [];
	rockStars[0] = prompt("Who is your favorite rock star?", "");
	/*
	Ask the user how many of this rockstar's cds she owns and store
	the result in a variable.
	*/
	rockStars[1] = prompt("And your next favorite rock star?", "");
	/*
	Ask the user how many of this rockstar's cds she owns and store
	the result in a variable.
	*/
</script>
</head>
<body>
<!--
	Let the user know how many more of her favorite rockstar's albums
	she has than of her second favorite rockstar's cds.
-->
</body>
</html>

Code Explanation

Challenge

  1. Open VariablesArraysOperators/Exercises/Operators-challenge.html for editing.
  2. Modify it so that it outputs an unordered list as shown below:Unordered List

Solution:

VariablesArraysOperators/Solutions/Operators.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript Operators</title>
<link href="style.css" rel="stylesheet">
<script>
	var rockStars = [];
	var cdTotals = [];
	rockStars[0] = prompt("Who is your favorite rock star?", "");
	cdTotals[0] = prompt("How many " + rockStars[0] + " cds do you own?", "");
	rockStars[1] = prompt("And your next favorite rock star?", "");
	cdTotals[1] = prompt("How many " + rockStars[1] + " cds do you own?", "");
</script>
</head>
<body>
	<script>
	var diff = cdTotals[0] - cdTotals[1];
	document.write("You have " + diff + " more cds of " + rockStars[0]);
	document.write(" than you have of " + rockStars[1] + ".");
	</script>
</body>
</html>

Code Explanation

Challenge Solution:

VariablesArraysOperators/Solutions/Operators-challenge.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript Operators</title>
<link href="style.css" rel="stylesheet">
<script>
	var userNum1 = window.prompt("Choose a number.", "");
	alert("You chose " + userNum1);
	var userNum2 = window.prompt("Choose another number.", "");
	alert("You chose " + userNum2);
	var numsAdded = userNum1 + userNum2;
	var numsSubtracted = userNum1 - userNum2;
	var numsMultiplied = userNum1 * userNum2;
	var numsDivided = userNum1 / userNum2;
	var numsModulused = userNum1 % userNum2;
</script>
</head>
<body>
<ul>
	<script>
		document.write("<li>" + userNum1 + " + " + userNum2 + " = ");
			document.write(numsAdded + "</li>");
		document.write("<li>" + userNum1 + " - " + userNum2 + " = ");
			document.write(numsSubtracted + "</li>");
		document.write("<li>" + userNum1 + " * " + userNum2 + " = ");
			document.write(numsMultiplied + "</li>");
		document.write("<li>" + userNum1 + " / " + userNum2 + " = ");
			document.write(numsDivided + "</li>");
		document.write("<li>" + userNum1 + " % " + userNum2 + " = ");
			document.write(numsModulused + "</li>");
	</script>
</ul>
</body>
</html>