• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 6. Expressions, Conditions, Oper... > Revisiting Strings and Numbers

Revisiting Strings and Numbers

Let's quickly revisit strings and numbers with an example of a very simple JavaScript calculator! In this example, you'll not only look at a way to use operators but you will also find out how you can change string digits to numbers through a process called type conversion.


The JavaScript Calculator

1.
Start off with the bare HTML template:

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!-- Cloaking device on!

// Cloaking device off -->
</script>
</head>
<body>

</body>
</html>

2.
Declare the variables you will use here. You should have two variables for each of the numbers the user will input—one for the operator the user wants to use and a final one to hold the answer:

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!-- Cloaking device on!
var num1, op, num2, ans;
// Cloaking device off -->
</script>
</head>
<body>

</body>
</html>

3.
Next, use the prompt() method to prompt the user for the first number to enter, and assign this to the variable num1:

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!-- Cloaking device on!
var num1, op, num2, ans;
num1 = prompt("Enter a number:","a number");
// Cloaking device off -->
</script>
</head>
<body>

</body>
</html>

4.
Add another prompt, this time to ask for the operator to use. Assign this value to the variable op:

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!-- Cloaking device on!
var num1, op, num2, ans;
num1 = prompt("Enter a number:","a number");
op = prompt("Enter an operator (+, -, *, / and %)", "operator");
// Cloaking device off -->
</script>
</head>
<body>

</body>
</html>

5.
Next, add another prompt for the second number. This is assigned to num2:

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!-- Cloaking device on!
var num1, op, num2, ans;
num1 = prompt("Enter a number:","a number");
op = prompt("Enter an operator (+, -, *, / and %)", "operator");
num2 = prompt("Enter another number:", "a number");
// Cloaking device off -->
</script>
</head>
<body>

</body>
</html>

6.
Now, perform the sum. Here you must evaluate the sum using the method eval(). This method does the math for you. However, before you can do the math, you need to change the string variables num1 and num2 into numbers. You can do this by declaring them as numbers. The result of the evaluation is passed to the variable ans:


PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint