JavaScript Examples and Exercises
JavaScript Examples
Example 1: Adding two numbers
The following example shows you how to use alert(), prompt(), document.writeln()
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>JavaScript Example - adding two numbers</title> </head> <body> <script type="text/javascript"> document.writeln("<h1>Using JavaScript prompt</h1>") document.writeln("<h2>Adding two numbers</h2>"); a = prompt("Enter a number"); b = prompt("Enter another number"); //must parse the above values to int a = parseInt(a); b = parseInt(b); //Show the result in alert box alert(a+b); //Show the result in the page document.writeln("Sum of a+b = "); c = a + b; document.write(c); </script> </body> </html>
Example 2: Using built in JavaScript objects and functions
JavaScript provides a large number of built-in and ready to use JavaScript classes and functions.
For example in the above example we have used the following: alert() and prompt() which are examples of functions.
There are also some other examples of functions from the above example which are parseInt(), write and writeln of the document object.
In this example we show you how to use some library objects such as Date and functions such as sqrt from the Math object
<script type="text/javascript"> document.writeln("<h1>Using JavaScript classes</h1>") document.writeln("<h2>The Date class</h2>"); var now = new Date(); document.writeln("<br>Todays date is:" +now); hours = now.getHours(); minutes = now.getMinutes(); document.writeln("<br>The time now is:"+hours+":"+minutes); num = prompt("Enter a number"); //must parse the above value to int a = parseInt(num); document.writeln("<br>Square root of "+num+"= "+Math.sqrt(a)); document.writeln("<br>Square of "+num+"= "+(a*a)); </script>
Writing your own functions
The following code show example of two functions add and product
Exercise: add functions for division and subtracting
<html> <head> <script type="text/javascript"> function add(a,b) { return a + b; } function product(a,b) { alert(a * b); //show the product of a and b in an alert box } </script> </head> <body> <h1>JavaScript functions example</h1> <script type="text/javascript"> document.writeln("Sum of 4 and 3 = "+add(4,3)); </script> <p> The following is an example of calling a function on an event - the onClick event on the hyperlink below <br /> <a href="#" onclick="javascript:product(4,3)">Click here to see 3 * 4</a> </p> </body> </html>





