JavaScript Primers #14

By Joe Burns

http://www.htmlgoodies.com/primers/jsp/article.php/3478261/JavaScript-Primers-14.htm (Back to article)

Use these to jump around or read it all


The Concept
The Script
The Script's Effect
Deconstructing the Script
What You've Learned
Your Assignment


The Concept

This page will not only show you how to use numeric values to perform computations with JavaScript, but it will also test your basic math skills. There may be a test later.... Its purpose is to introduce you to variables, something you'll use often. If you've done any programming, you should be experiencing deja vu! If not, don't panic. This is an easy introduction!


The Script

<BODY>
   <SCRIPT type="text/javascript">
       var numsums = 10 + 2
            alert("10 + 2 is " + numsums)
       var x = 10
            alert("ten is " + x)
       var y = x * 2
            alert("10 X 2 = " + y)
       var z = "Hello " + "Good Bye"
      alert(z)
   </SCRIPT>
</BODY>

The Script's Effect

Try to figure out the value of each of the variables before running this script.


Deconstructing the Script

<BODY>
   <SCRIPT type="text/javascript">
       var numsums = 10 + 2
            alert("10 + 2 is " + numsums)
       var x = 10
            alert("ten is " + x)
       var y = x * 2
            alert("10 X 2 = " + y)
       var z = "Hello " + "Good Bye"
      alert(z)
   </SCRIPT>
</BODY>

Here's the quick rundown. The script sets a variable for "numsums." Can you see that it is equal to 12 (10+2)? It then transfers that variable to an alert method and displays that 10 + 2 = the variable or 12. With me?

Another variable, "x", is set to equal 10. The alert method then displays that value.

Another variable, "y", is set to equal the "x" variable multiplied by 2. That should be twenty, right? That answer then displays in the alert method.

Finally, the variable "z" is created showing you can connect text using the computation symbols. That variable is then displayed using the alert methods.

Did you see all that working? Run the script again and you'll see each alert pop up using the variables created through computational symbols.

Here's the Deal:


What You Have Learned


Your Assignment

Rewrite the JavaScript above as a function. You may change some of the math to experiment with division, if you wish. Include a Welcome message in the body of your HTML document. Use the OnLoad event to run your function.

Here's a possible answer
(this will open a new window)


The Concept
The Script
The Script's Effect
Deconstructing the Script
What You've Learned
Your Assignment

On To JavaScript Primer #15