From Wikipedia, the free encyclopedia
Jump to: navigation, search

JavaScript is a scripting language for computers. It is often run in web browser applications to create dynamic content like a popup message or a live clock. It is not related to the programming language Java.

Example[change | change source]

This script writes "Example" on the screen. The lines that start with // are comments; they show someone reading the code what the code does.

 1 <script type="text/javascript">
 2 function example()
 3 {
 4     var ex = document.createTextNode('Example'); //make the computer remember "Example", 
 5                                                  //so whenever you say "ex" the computer will append it with "Example"
 6     document.body.appendChild(ex);               //put the text on the bottom of the webpage
 7 }
 8 example(); 
10 /*
11  * The code below does almost the same thing as the code above, 
12  * but it shows "Example" in a popup box and is shorter.
13  *
14  * This is a comment too, by the way.
15  */
17 alert("Example");
18 </script>

The JavaScript is enclosed by <script></script> tags, to tell that it is a script and not text to be put onto the web page the JavaScript is running on. This script inserts the numbers 1 through 10 at the bottom of a webpage:

 1 <script type="text/javascript">
 2 for(var numOfTimesAround = 1; numOfTimesAround <= 10; numOfTimesAround++){
 4 document.body.innerHTML = document.body.innerHTML + numOfTimesAround + "<br>";
 5 /*
 6 * This puts the number, then a new line, at the end of the web page.
 7 * In javascript, using the + sign combines two words together.
 8 * So writing "Hello" + " World" would make "Hello World".
 9 * Or, writing 1 + "<br>" makes "1<br>", which is what we want.
10 */
12 }
14 </script>

The for() loop makes whatever code is between the { and the } happen more than one time. In this case, it keeps looping until numOfTimesAround is equal to 10, then it stops.

Differences between Java and Javascript[change | change source]

  • In Java, to make a variable (to make a computer remember something), you have to say what type of variable it is: a number, a word, a letter, or more. In JavaScript, this is not necessary.
  • In JavaScript, functions are stored as variables (unlike Java). This makes the following code okay in JavaScript:
function sayHi(){
sayHi = function(){
//alerts "Bye!" instead of "hi!" without giving an error
  • JavaScript runs in a web browser, but Java runs directly on a computer.
  • JavaScript is interpreted, but Java, in most cases, must be compiled.

Related pages[change | change source]

Other websites[change | change source]