JavaScript

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 message boxes popping up or a live clock. It is not related to and is different from the programming language Java.

Example[change | edit 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.

<script type="text/javascript">
function example()
{
    var ex = document.createTextNode('Example'); //make the computer remember "Example", so whenever you say "ex" the computer will replace it with "Example"
    document.body.appendChild(ex);               //put the text on the bottom of the webpage
}
example(); 
 
/*
 * The code below does almost the same thing as the code above, 
 * but it shows "Example" in a popup box and is shorter.
 *
 * This is a comment too, by the way.
 */
 
alert("Example");
</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 puts the numbers 1 through 10 at the bottom of a webpage:

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

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

Differences between Java and Javascript[change | edit 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, you don't need to do that.
  • In javascript, functions are stored as variables. This makes the following code okay in javascript:
function sayHi(){
alert("hi!");
}
sayHi = function(){
alert("Bye!");
}
sayHi();
//alerts "Bye!" instead of "hi!" without giving an error
  • Javascript runs in a web browser, but java runs on a computer.

Other pages[change | edit source]

Other websites[change | edit source]