Working with Operators - Exercise

Working with Operators - Exercise

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 albums 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 albums 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>
<meta charset="UTF-8">
<title>JavaScript Operators</title>
<script type="text/javascript">
var rockStars = [];
rockStars[0] = prompt("Who is your favorite rock star?", "");
/*
Ask the user how many of this rockstar's albums 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 albums she owns and store
the result in a variable.
*/
</script>
<body>
<!--
Let the user know how many more of her favorite rockstar's albums
she has than of her second favorite rockstar's albums.
-->
</body>
</html>```

Challenge

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

Solution:

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

Challenge Solution:

VariablesArraysOperators/Solutions/Operators-challenge.html
```<!DOCTYPE HTML>
<html>
<meta charset="UTF-8">
<title>JavaScript Operators</title>
<script type="text/javascript">
var userNum1 = window.prompt("Choose a number.", "");
var userNum2 = window.prompt("Choose another number.", "");
var numsAdded = Number(userNum1) + Number(userNum2);
var numsSubtracted = userNum1 - userNum2;
var numsMultiplied = userNum1 * userNum2;
var numsDivided = userNum1 / userNum2;
var numsModulused = userNum1 % userNum2;
</script>
<body>
<ul>
<script type="text/javascript">
document.write("<li>" + userNum1 + " + " + userNum2 + " = ");