facebook 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, dominantHand;

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

age = 18;

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

var age = 18;

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.

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

var strAge = "18";

If you were to try to do a math function on strAge (e.g., multiply it by 4), a strongly typed (or statically typed) language would error saying you cannot multiply a string by a number. JavaScript would dynamically change strAge to an integer for the purposes of that operation. Although this is very convenient, it can also cause unexpected results, so be careful.

TypeScript

TypeScript is an open-source programming language developed by Microsoft. Developers writing in TypeScript compile their code to valid JavaScript, which they can use anywhere one might use JavaScript. A useful feature of TypeScript is static typing, meaning that a developer might specify the type of a given variable - to be a string, say, or a Boolean true/false variable - when declaring the variable. Violations of this static typing - trying to work with a number value as if it were a string value, for example - produces an error when compiling the TypeScript code into JavaScript, and thus adds a check against a dangerous bug creeping into the code.

Google Chrome DevTools

Google Chrome DevTools is a set of tools to help web developers. We will use the Chrome DevTools Console to illustrate JavaScript's dynamic typing.

To open the Chrome DevTools Console:

  1. Click on the three-vertical-dot icon in the upper right of Google Chrome.
  2. Select More Tools.
  3. Select Developer Tools.Chrome DevTools
  4. The tools will usually be docked on the right or bottom of your screen. Make sure that the Console is selected:Google Developer Tools ConsoleYou may need to dropdown the menu to see the Console option:Google DevTools Menu
  5. Now type "gobbledygook" in the Console and press Enter:gobbledygookThe word "gobbledygook" doesn't mean anything in JavaScript and we have not defined a variable named "gobbledygook", so we get an error.
  6. To clear the Console, press the Clear Console icon:Clear Chrome Console
  7. You should now have a clear Console to start practicing JavaScript:Chrome Console Cleared

You can write and test JavaScript for a page directly in the Console. We will use it to show how JavaScript variables are dynamic:

  1. Type var age = 18; and press Enter:declaring ageDon't worry about the "undefined" response. All that means is that your code didn't return anything.
  2. Now type age; and press Enter:showing age This time it does return something - the value of age.
  3. Let's subtract 2 from age and then add 2 to age:Adding and SubtractingThat works as expected.
  4. Now we will set age to '18' in quotes. This makes age a string, which is programming-speak for text:Set age to String Notice that it returns "18". At this point, a strongly typed programming language would have balked. It would have told us that age was declared as a number and cannot be assigned a string value. You may also notice that "18" in double quotes was returned even though we used single quotes when we set the value of age. Single and double quotes are interchangeable in JavaScript.
  5. Now let's subtract 2 from age:2 Subtracted Notice that JavaScript understands that we want to treat age as a number and so it converts it to a number before doing the math.
  6. Now let's add 2 to age:Addition with StringOops! What happened? As it turns out, the plus operator (+) has multiple functions in JavaScript. In addition to adding numbers together, it can add strings together. In this case, because age is a string, it converts 2 to a string before doing the operation. So, it's adding "18" and "2" to give us "182".

The issue shown above does not come up often, but when it does, it can bite you. The best way to handle it is to make sure that when you are going to use a variable as a new type, you explicitly convert it to the new type. We will show how to do that later in the course.

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 variable names.

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 button elements.

Code Sample:

VariablesArraysOperators/Demos/variables.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="../normalize.css">
<link rel="stylesheet" href="../styles.css">
<script>
  //Pop up a prompt
  var userColor = window.prompt("Enter a color.", "");
</script>
<title>JavaScript Variables</title>
</head>
<body>
<main>
  <button onclick="document.body.style.backgroundColor = 'red';">
    Red
  </button>
  <button onclick="document.body.style.backgroundColor = 'white';">
    White
  </button>
  <button onclick="document.body.style.backgroundColor = 'green';">
    Green
  </button>
  <button onclick="document.body.style.backgroundColor = 'blue';">
    Blue
  </button>
  <button onclick="document.body.style.backgroundColor = userColor;">
  <script>
    document.write(userColor);
  </script>
  </button>
</main>
</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 (i.e., "").

If the OK button is pressed, the prompt returns the value entered in the text box. If the Cancel button, the prompt returns null (See null callout below.). 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 button element, which has an onclick on-event handler that will be used to turn the background color of the page to the user-entered color.

<button
  onclick="document.body.style.backgroundColor = userColor;">
<script>
  document.write(userColor);
</script>
</button>

Test this out:

  1. Open VariablesArraysOperators/Demos/variables.html in your browser and enter "Yellow" in the prompt:prompt: yellow
  2. The resulting page should appear as follows:page: yellow
  3. Click the "Yellow" button. The background should turn yellow.

null

In JavaScript,null is a datatype with only one value: null. It represents a value that we don't know or that is missing.

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 lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="../normalize.css">
<link rel="stylesheet" href="../styles.css">
<script>
  //ADD PROMPT HERE
</script>
<title>JavaScript Variables</title>
</head>
<body>
<main>
  <button onclick="alert('Paul');">Paul</button>
  <button onclick="alert('John');">John</button>
  <button onclick="alert('George');">George</button>
  <button onclick="alert('Ringo');">Ringo</button>
  <!--ADD BUTTON HERE-->
</main>
</body>
</html>

Code Explanation

Solution:

VariablesArraysOperators/Solutions/variables.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="../normalize.css">
<link rel="stylesheet" href="../styles.css">
<script>
  var firstName = window.prompt("What's your name?", "");
</script>
<title>JavaScript Variables</title>
</head>
<body>
<main>
  <button onclick="alert('Paul');">Paul</button>
  <button onclick="alert('John');">John</button>
  <button onclick="alert('George');">George</button>
  <button onclick="alert('Ringo');">Ringo</button>
  <button onclick="alert(firstName);">Your Name</button>
</main>
</body>
</html>

Constants

In programming, a constant is like a variable in that it is an identifier that holds a value, but, unlike variables, constants are not variable, they are constant. Good name choices, right?

Whereas variables are declared with the var keyword, constants are declared with the const keyword:

const NUM = 1;

Constants cannot be reassigned; that is, a later statement like NUM = 2; would fail, meaning that the value of 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. In Google Chrome, for example, trying to assign a new value to a constant will cause an error. We can see this using the Chrome DevTools Console: constant

While constants can be declared with uppercase or lowercase names, the convention is to use all-uppercase names for constants, so they are easily distinguishable from variables.

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. Note that, unlike in some languages, values in JavaScript arrays do not all have to be of the same data type.

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 colors array. It then displays the values in the colors array in the buttons and assigns them to document.body.style.backgroundColor when the user clicks on the buttons.

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 colors = new Array();
  colors[0] = prompt("Choose a color.", "");
  colors[1] = prompt("Choose a color.", "");
  colors[2] = prompt("Choose a color.", "");
  colors[3] = prompt("Choose a color.", "");
</script>
<title>JavaScript Arrays</title>
</head>
<body>
<main>
  <button onclick="document.body.style.backgroundColor = colors[0];">
  <script>
    document.write(colors[0]);
  </script>
  </button> |
  <button onclick="document.body.style.backgroundColor = colors[1];">
  <script>
    document.write(colors[1]);
  </script>
  </button> |
  <button onclick="document.body.style.backgroundColor = colors[2];">
  <script>
    document.write(colors[2]);
  </script>
  </button> |
  <button onclick="document.body.style.backgroundColor = colors[3];">
  <script>
    document.write(colors[3]);
  </script>
  </button>
</main>
</body>
</html>

Code Explanation

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

colors = new Array();

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

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

The body of the page contains a paragraph with four <button> tags, the text of which is dynamically created with values from the colors array.

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 code below, written in Chrome DevTools Console, illustrates how an associative array is used: Associative Array

Arrays can also have subarrays. For example, rather than having "singer1" and "singer2" keys, it would be better to have a "singers" key that was an enumerative array. We could do that like this:Associative Array with subarray

Notice how the singers are accessed first by the "singers" key of the beatles array and then by the index:

beatles['singers'][0];

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
unshift() Prepends one or more items to the beginning of an array.
beatles.unshift('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.
beatles.slice(1, 3) //Returns [John, George]
splice(start, count) Removes count items from start in the array and returns the resulting array.
beatles.splice(1, 2) //Returns [Paul, Ringo]
sort() Sorts an array alphabetically.
beatles.sort() //Returns [George, John, Paul, Ringo] and sorts the 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. It should work as follows:
    1. As the page loads, you should get four alerts: Rockstar 1 Rockstar 2 Rockstar 3 Rockstar 4
    2. After responding to all the prompts, you should see four buttons on the page. When you click one of the buttons, it should alert one of your rockstars: Rockstar alert

Code Sample:

VariablesArraysOperators/Exercises/arrays.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="../normalize.css">
<link rel="stylesheet" href="../styles.css">
<script>
  /*
    Declare a rockStars array and populate it with 
    four values entered by the user.
  */
</script>
<title>JavaScript Arrays</title>
</head>
<body>
<main>
  <button>Favorite</button>
  <button>Next Favorite</button>
  <button>Next Favorite</button>
  <button>Next Favorite</button>
</main>
</body>
</html>

Code Explanation

Solution:

VariablesArraysOperators/Solutions/arrays.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="../normalize.css">
<link rel="stylesheet" href="../styles.css">
<script>
  var rockStars = new Array();
  rockStars[0] = prompt("Who is your favorite rock star?", "");
  rockStars[1] = prompt("Your next favorite rock star?", "");
  rockStars[2] = prompt("Your next favorite rock star?", "");
  rockStars[3] = prompt("Your next favorite rock star?", "");
</script>
<title>JavaScript Arrays</title>
</head>
<body>
<main>
  <button onclick="alert(rockStars[0]);">Favorite</button>
  <button onclick="alert(rockStars[1]);">Next Favorite</button>
  <button onclick="alert(rockStars[2]);">Next Favorite</button>
  <button onclick="alert(rockStars[3]);">Next Favorite</button>
</main>
</body>
</html>

Playing with Array Methods

Take some time to play around with these array methods in Chrome DevTools Console. Try your own things and/or follow along with the code below.

Array Methods

Note that some methods will return a value without modifying the existing array, while others will make changes to the existing array "in place". For example, study the code below. Notice that slice() returns a new array without changing the existing array, whereas splice() and sort() make changes to the existing array. More Array Methods

Array Documentation

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array for full documentation on Arrays.

JavaScript Operators

Arithmetic Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (remainder)
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)
++ Increment by one (a++ is the same as a=a+1 or a+=1)
-- Decrement by one (a-- is the same as a=a-1 or a-=1)
String Operators
Operator Description
+ Concatenation
var greeting = "Hello " + firstname;
+= One step concatenation and assignment
var greeting = "Hello ";
greeting += firstname;

The code below, written in Chrome DevTools Console, shows examples of working with JavaScript arithmetic operators:Arithmetic Operators

And here we have examples of the concatenation operator:Concatenation Operator

The Modulus Operator

The modulus operator (%) is used to find the remainder after division.

For example 5 divided by 2 is equal to 2 with a remainder of 1. So, 5 % 2 is equal to 1:

5 % 2 // returns 1
11 % 3 // returns 2
22 % 4 // returns 2
22 % 3 // returns 1
10934 % 324 // returns 242

The modulus operator is useful for determining whether a number is even or odd:

1 % 2 // returns 1: odd
2 % 2 // returns 0: even
3 % 2 // returns 1: odd
4 % 2 // returns 0: even
5 % 2 // returns 1: odd
6 % 2 // returns 0: even

Playing with Operators

Take some time to play around with JavaScript operators in Chrome DevTools Console. Try your own things and/or follow along with the code above.

The file below illustrates the use of the concatenation operator and several math operators. It also illustrates a potential problem with loosely typed languages.

Code Sample:

VariablesArraysOperators/Demos/operators.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="../normalize.css">
<link rel="stylesheet" href="../styles.css">
<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>
<title>JavaScript Operators</title>
</head>
<body>
<main>
  <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>
</main>
</body>
</html>

Code Explanation

This page is processed as follows:

  1. The user is prompted for a number and the result is assigned to userNum1:Operators Demo 1
  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:Operators Demo 2
  3. The user is prompted for another number and the result is assigned to userNum2:Operators Demo 3
  4. Another alert pops up telling the user what number she entered:Operators Demo 4
  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:Operators Demo 5

So, 5 + 4 is 54?? Well, only if 5 and 4 are strings, and, as stated earlier, all user-entered data is treated as a string. Don't worry. We will learn how to fix this problem soon.

The Default Operator

Default Operator
Operator Description
|| Used to assign a default value.
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.

Why do we need a default operator?

The default operator allows you to make sure that your variable contains a non-null value, so that you can perform operations on the variable with no errors. To illustrate, do the following in the Chrome DevTools Console:

  1. Enter
    var firstName = prompt("First Name:","");
    and press Enter. This will cause a prompt to pop up.prompt code
  2. Press the Cancel button. This will return null and assign it to firstName.First Name Prompt
  3. Enter
    var greeting = "Hello, " + firstName;
    and press Enter.
  4. Then output greeting and you'll see this strange result:console greeting

Now repeat the above, but start with:

var firstName = prompt("First Name:","") || "Stranger";

This time, when you press Cancel, the default value of "Stranger" will be assigned to firstName and the concatenation operation will work fine.console greeting 2

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 songs she has downloaded of her favorite and second favorite rockstars:Operators Exercise 1 Operators Exercise 2 Operators Exercise 3 Operators Exercise 4
  3. In the body, let the user know how many more of her favorite rockstar's songs she has than of her second favorite rockstar's songs:Operators Exercise 5
  4. Test your solution in a browser.

Code Sample:

VariablesArraysOperators/Exercises/operators.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="../normalize.css">
<link rel="stylesheet" href="../styles.css">
<script>
  var rockStars = [];
  rockStars[0] = prompt("Who is your favorite rock star?", "");
  /*
  Ask the user how many of this rockstar's songs she has downloaded
  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 songs she has downloaded
  and store the result in a variable.
  */
</script>
<title>JavaScript Operators</title>
</head>
<body>
<main>
<!--
  Let the user know how many more of her favorite rockstar's songs
  she has than of her second favorite rockstar's songs.
-->
</main>
</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:Operator Challenge Don't worry about the 54. We will learn how to fix the addition problem soon.

Solution:

VariablesArraysOperators/Solutions/operators.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="../normalize.css">
<link rel="stylesheet" href="../styles.css">
<script>
  var rockStars = [];
  var songTotals = [];
  rockStars[0] = prompt("Who is your favorite rock star?", "");
  songTotals[0] = prompt("How many " + rockStars[0] + " songs do you have?", "");
  rockStars[1] = prompt("And your next favorite rock star?", "");
  songTotals[1] = prompt("How many " + rockStars[1] + " songs do you have?", "");
</script>
<title>JavaScript Operators</title>
</head>
<body>
<main>
  <script>
  var diff = songTotals[0] - songTotals[1];
  document.write("You have " + diff + " more songs of " + rockStars[0]);
  document.write(" than you have of " + rockStars[1] + ".");
  </script>
</main>
</body>
</html>

Code Explanation

Challenge Solution:

VariablesArraysOperators/Solutions/operators-challenge.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="../normalize.css">
<link rel="stylesheet" href="../styles.css">
<script>
  var userNum1 = prompt("Choose a number.", "");
  alert("You chose " + userNum1);
  var userNum2 = 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>
<title>JavaScript Operators</title>
</head>
<body>
<main>
<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>
</main>
</body>
</html>