JavaScript

Tuesday April 8, 2025
updated: April 10, 2002

 
Home
Getting Started
Lesson 1
Lesson 2
Lesson 3
Lesson 4
Lesson 5
Lesson 6
Lesson 7
Lesson 8
Resources
Credits

 

 


Lesson 4 Example: Operators

CODE

RESULT

<Script>
<!-- Variable declaration -->
var x, y, z
x = prompt("Enter first number")
y = prompt("Enter second number")
x=parseInt(x)
y=parseInt(y)
z = eval(x+y)
alert("The sum of " +x+ " and" +y+ "is" +(eval("x+y")
</Script>

    • In the first line the variables are declared
    • Then the variables are assigned values. The value will be whatever the user types into the prompt box.
    • Prompt() is used to call a prompt box to open. The text in quotation marks will be displayed in the prompt box.
    • Then parseInt () is used to assign the variables as integers. If this is not done x and y would be treated like a string, and could not be added together.
    • Then the value of z is assigned
    • eval() is used to calculate a mathematical operation, in this case the addition of x and y.
    • Finally the alert box displays the message.

© 2002 Tracy Johnson