If you redeclare a JavaScript variable, it will not lose its original value.

var x=5;
var x;

After the execution of the statements above, the variable x will still have the value of 5. The value of x is not reset (or cleared) when you redeclare it.




If you assign values to variables that have not yet been declared, the variables will automatically be declared.

These statements:

x=5;
carname="Volvo";

have the same effect as:

var x=5;
var carname="Volvo";


Creating variables in JavaScript is most often referred to as "declaring" variables.

You can declare JavaScript variables with the var statement:

var x;
var carname;

After the declaration shown above, the variables are empty (they have no values yet).

However, you can also assign values to the variables when you declare them:

var x=5;
var carname="Volvo";

After the execution of the statements above, the variable x will hold the value 5, and carname will hold the value Volvo.

Note: When you assign a text value to a variable, use quotes around the value.



As with algebra, JavaScript variables are used to hold values or expressions.

A variable can have a short name, like x, or a more descriptive name, like carname.

Rules for JavaScript variable names:

  • Variable names are case sensitive (y and Y are two different variables)
  • Variable names must begin with a letter or the underscore character

Note: Because JavaScript is case-sensitive, variable names are case-sensitive.



Do you remember algebra from school? x=5, y=6, z=x+y

Do you remember that a letter (like x) could be used to hold a value (like 5), and that you could use the information above to calculate the value of z to be 11?

These letters are called variables, and variables can be used to hold values (x=5) or expressions (z=x+y).



In the following example the comment is placed at the end of a code line:
Example
<script type="text/javascript">
document.write("Hello"); // Write "Hello"
document.write(" Dolly!"); // Write " Dolly!"
</script>


In the following example the comment is used to prevent the execution of a single code line (can be suitable for debugging):
Example
<script type="text/javascript">
//document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>");
</script> 

In the following example the comment is used to prevent the execution of a code block (can be suitable for debugging):
Example
<script type="text/javascript">
/*
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>");
*/
</script> 


Multi line comments start with /* and end with */.

The following example uses a multi line comment to explain the code:
Example
<script type="text/javascript">
/*
The code below will write
one heading and two paragraphs
*/
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>");
</script> 


Comments can be added to explain the JavaScript, or to make the code more readable.

Single line comments start with //.

The following example uses single line comments to explain the code:
Example
<script type="text/javascript">
// Write a heading
document.write("<h1>This is a heading</h1>");
// Write two paragraphs:
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>");
</script> 


JavaScript statements can be grouped together in blocks.

Blocks start with a left curly bracket {, and ends with a right curly bracket }.

The purpose of a block is to make the sequence of statements execute together.

This example will write a heading and two paragraphs to a web page:
Example
<script type="text/javascript">
{
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>");
}
</script> 


JavaScript code (or just JavaScript) is a sequence of JavaScript statements.

Each statement is executed by the browser in the sequence they are written.

This example will write a heading and two paragraphs to a web page:
Example
<script type="text/javascript">
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>");
</script> 


A JavaScript statement is a command to a browser. The purpose of the command is to tell the browser what to do.

This JavaScript statement tells the browser to write "Hello Dolly" to the web page:

document.write("Hello Dolly");

It is normal to add a semicolon at the end of each executable statement. Most people think this is a good programming practice, and most often you will see this in JavaScript examples on the web.

The semicolon is optional (according to the JavaScript standard), and the browser is supposed to interpret the end of the line as the end of the statement. Because of this you will often see examples without the semicolon at the end.

Note: Using semicolons makes it possible to write multiple statements on one line.



Unlike HTML, JavaScript is case sensitive - therefore watch your capitalization closely when you write JavaScript statements, create or call variables, objects and functions.


JavaScripts in a page will be executed immediately while the page loads into the browser. This is not always what we want. Sometimes we want to execute a script when a page loads, other times when a user triggers an event.

Scripts in <head>

Scripts to be executed when they are called, or when an event is triggered, go in the head section.

If you place a script in the head section, you will ensure that the script is loaded before anyone uses it.
Example
<html>
<head>
<script type="text/javascript">
function message()
{
alert("This alert box was called with the onload event");
}
</script>
</head>

<body onload="message()">
</body>
</html>


Scripts in <body>

Scripts to be executed when the page loads go in the body section.

If you place a script in the body section, it generates the content of a page.
Example
<html>
<head>
</head>

<body>
<script type="text/javascript">
document.write("This message is written by JavaScript");
</script>
</body>

</html>

Scripts in <head> and <body>

You can place an unlimited number of scripts in your document, so you can have scripts in both the body and the head section.
<html>
<head>
<script type="text/javascript">
....
</script>
</head>
<body>
<script type="text/javascript">
....
</script>
</body>

Using an External JavaScript

If you want to run the same JavaScript on several pages, without having to write the same script on every page, you can write a JavaScript in an external file.

Save the external JavaScript file with a .js file extension.

Note: The external script cannot contain the <script> tag!

To use the external script, point to the .js file in the "src" attribute of the <script> tag:
Example
<html>
<head>
<script type="text/javascript" src="xxx.js"></script>
</head>
<body>
</body>
</html>


The example below shows how to use JavaSript to write text on a web page:

Example



<html>
<body>
<script type=" text/javascript">
document.write(" Hello World!");
</script>
</body>
</html> 


The example below shows how to add HTML tags to the JavaScript:

Example



<html>
<body>
<script type="text/javascript">
document.write("<h1>Hello World!</h1>");
</script>
</body>
</html>


To insert a JavaScript into an HTML page, we use the <script> tag. Inside the <script> tag we use the type attribute to define the scripting language.

So, the <script type="text/javascript"> and </script> tells where the JavaScript starts and ends:
<html>
<body>
<script type="text/javascript">
...
</script>
</body>
</html>

The document.write command is a standard JavaScript command for writing output to a page.

By entering the document.write command between the <script> and </script> tags, the browser will recognize it as a JavaScript command and execute the code line. In this case the browser will write Hello World! to the page:
<html>
<body>
<script type="text/javascript">
document.write("Hello World!");
</script>
</body>
</html>


JavaScript's official name is ECMAScript.

ECMAScript is developed and maintained by the ECMA organization.

ECMA-262 is the official JavaScript standard.

The language was invented by Brendan Eich at Netscape (with Navigator 2.0), and has appeared in all Netscape and Microsoft browsers since 1996.

The development of ECMA-262 started in 1996, and the first edition of was adopted by the ECMA General Assembly in June 1997.

The standard was approved as an international ISO (ISO/IEC 16262) standard in 1998.

The development of the standard is still in progress.



  • JavaScript gives HTML designers a programming tool - HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into their HTML pages
  • JavaScript can put dynamic text into an HTML page - A JavaScript statement like this: document.write("

    " + name + "

    ") can write a variable text into an HTML page
  • JavaScript can react to events - A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element
  • JavaScript can read and write HTML elements - A JavaScript can read and change the content of an HTML element
  • JavaScript can be used to validate data - A JavaScript can be used to validate form data before it is submitted to a server. This saves the server from extra processing
  • JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load another page specifically designed for that browser
  • JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve information on the visitor's computer


NO!

Java and JavaScript are two completely different languages in both concept and design!

Java (developed by Sun Microsystems) is a powerful and much more complex programming language - in the same category as C and C++.



What exactly is Javascript?:
Javascript is a programming language that is used to make web pages interactive. It runs on your visitor's computer and so does not require constant downloads from your web site.

Are Javascript and Java the same?:
No, they are two completely different computer languages. Only their names are similar.

What do I need to run Javascript?:
Javascript support is built right into web browsers. Provided that the visitors to your site are using web browsers that support Javascript (most do) and have Javascript enabled (it is by default) then your Javascript will run.

Do I need to learn Javascript to be able to use it?:

No. There are plenty of Javascripts that have already been written that people have made available for you to plug straight into your web page. All you need to know to be able to use such scripts is how to paste the supplied code into the required places in your web page.

What do I need to write Javascript?:

Javascript is an interpreted language and so no special program is required to be able to create usable code. Any plain text editor such as Notepad is quite satisfactory for being able to write Javascript. That said, an editor which colourizes the code to make it easier to see what is what makes it easier to find your mistakes but then my Javascript Formatter can reformat your script to make errors even easier to spot.

Can I use HTML instead of Javascript?:

No. HTML and Javascript are two completely different things. HTML is a markup language designed for defining static web page content. Javascript is a programming language designed for performing dynamic tasks.

Can I use PHP or some other server side language instead of Javascript?:

Perhaps, it depends on where the code needs to run. If it can run before the page loads you can use a server side language. If it has to run after the page has loaded then you must use Javascript as this is the only scripting language supported by all web browsers that support client side scripting.

Does the Javascript go in the same file as the HTML?:
It can but your scripts will be more easily reused on multiple pages of your site if you place them in separate files (using a .js extension helps identify them as Javascript). You then just link the Javascript to your HTML by inserting a


  • JavaScript is a scripting language, ideal for small programs used only from within Web browsers. A JavaScript script can't run alone, without the browser, the way a Java program does.

    JScript is Microsoft's implementation of JavaScript.

  • A Little History...
    In typical Web fashion, the evolutionary process of JavaScript has taken a somewhat lumpy path. When JavaScript started out life at Netscape, it was called LiveScript and its goal was to allow dynamic ("live") changes of Web pages and communication between the Web browser and plug-in applications ... such as Java. Java was hot and marketable, so in late 1995 Netscape got permission from Sun, the creators of Java, to use the word "Java" and Livescript became the *catchier* JavaScript.

    But along the way, JavaScript took on a life of its own. It was easier for non-programmers to learn than Java. It could add a lot of interactivity with little overhead. Like HTML code, JavaScript is contained within the HTML text file, so it can be easily added and modified. It became hot itself. And so now there's a move afoot to standardize JavaScript.

    More Than You Might Want to Know, But...
    Within the Web environment, the most common use of Java is to build applets, small programs that launch automatically from within a Web page. When the Web page loads, these applets are launched and begin to run on your local computer. While the applet runs, your browser sits quietly by.

    On the plus side, running a Java applet doesn't consume server time. It makes it possible for small, self-contained programs to be delivered via the Web, but run locally on individual computers. However, downloading Java applets has some people concerned about security; in corporate environments, Information Systems departments sometimes set up procedures to screen out external Java applets and prevent them from being downloaded. These IS managers fear (rightly or wrongly) that the applet could infect the system or be, in some way, a threat to the network.

    JavaScript, on the other hand, is attractive to Web developers because it is a scripting language rather than a self-executing program. The code is typically placed directly in the Web page—in fact, it requires a Web browser in order to run and it is designed to be fully-integrated with the browser. Because the JavaScript is physically located within the Web page, firewalls can't screen it out (although individual browsers can be configured to turn off JavaScript).



    JavaScript is an object-oriented scripting language that lets you build interactions between page content, the state of the browser, and the actions of the reader.

    In other words, JavaScript is a language that lets you make your pages interact with your readers and respond to what they do.

    It is a programming language that can make your pages feel more dynamic and give feedback to your user. This is a good argument for learning and incorporating it into your web techniques basket.

    It is a programming language that also has a learning curve in order for you to use it well. But don't let this scare you away from it—if you aren't a programmer, you can start out by learning a few basic concepts and then adapt existing JavaScript scripts for your needs.

    If you don't want to tackle JavaScript, that's OK too. You can still make attractive pages that your readers will like, using standard HTML. Don't let the "flavor of the month" mentality convince you that only programmers or big budget outfits can have a Web page. But take a look through this section—you might surprise yourself by knowing more about scripting than you think.

    What is JavaScript?

    • JavaScript was designed to add interactivity to HTML pages
    • JavaScript is a scripting language
    • A scripting language is a lightweight programming language
    • JavaScript is usually embedded directly into HTML pages
    • JavaScript is an interpreted language (means that scripts execute without preliminary compilation)
    • Everyone can use JavaScript without purchasing a license

    What You Should Already Know

    Before you continue you should have a basic understanding of the following:

    • HTML / XHTML