You are on page 1of 13

JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet

Explorer, Firefox, Chrome, Opera, and Safari.

What You Should Already Know


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

HTML and CSS

If you want to study these subjects first, find the tutorials on our Home page.

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

Are Java and JavaScript the same?


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 Can JavaScript do?



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 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

JavaScript = ECMAScript
JavaScript is an implementation of the ECMAScript language standard. ECMA-262 is the official JavaScript standard. JavaScript was invented by Brendan Eich at Netscape (with Navigator 2.0), and has appeared in all browsers since 1996. The official standardization was adopted by the ECMA organization (an industry standardization association) in 1997. The ECMA standard (called ECMAScript-262) was approved as an international ISO (ISO/IEC 16262) standard in 1998. The development is still in progress.

JAVASCRIPT COMPATIBILITY
Historically JavaScript compatibility has been a major problem for web developers. Variations between the official spec, the de-facto standard, and the various implementations have kept many a developer up all night. The end result is that many web pages don't work equally well, or at all, across browsers. The point is that JavaScript developers shouldnt have to detect and workaround such issues. JavaScript should work the same across all implementations. We believe this is the first step in making JavaScript better. To make it possible to achieve such implementation conformance, the first step is knowing where the divergences are. We in the JScript team are looking into where various browser based implementations diverge, where our engine is incorrect in its interpretation of the specification, what if any de facto compatibility conventions have been reached, and the value of codifying such conventions into the standard. Weve published the first draft of JScript Deviations from ES3 as a starting point. The document's title, "JScript Deviations from ES3", is a bit of a misnomer. This document covers not only IE, but also the JavaScript implementations found in Firefox, Opera, and Safari. This is an in-depth study of the spec with a point by point comparison between what is suppose to happen and what actually does, for all four browsers. *COPY(when text is copied) Firefox 3 has a lazy implementation. *CUT(when text is cut)

Firefox 3 has a lazy implementation. *ERROR(When the browser encounters a JavaScript error or a non-existent image file.) IE and Firefox have trouble with JavaScript errors in the traditional event registration model. Safari, Chrome, Opera and Konqueror do not support this event on JavaScript errors.

Variables
The most basic computer programming term is a variable. A variable can hold whatever we want it to. If we want to store our height, we would write: myHeight='6 foot'; If we want to store our wealth, we would write: money=100; myHeight is known as a string, because it contains letters, and money is a obviously a number. We need to be able to display the contents of a variable. There are several ways of doing this, but we shall begin by using document.write, which we have already met. document.write(xxxx) writes the value of xxxx to the current document. xxxx may contain dynamic data, i.e. a variable. So, <HTML> <HEAD> <TITLE>JavaScript Variables</TITLE> <SCRIPT> money=100; document.write('You have '+money+' dollars to spend.'); </SCRIPT> </HEAD> </HTML> This program displays 'You have 100 dollars to spend.'. JavaScript is known as a loosely-typed language, which means we don't have to declare whether our variable is string type or integer type. This is both a blessing and a curse. We could write: myHeight='6 foot'; myHeight=7;

This is legal in JavaScript. Equally: money=100; money='Fifty Quid'; is also legal. We can change the value of a variable whenever we want by resetting it. Here's a program that does just that. <HTML> <HEAD> <TITLE>Changing Variables</TITLE> <SCRIPT> money=100; document.write('You have '+money+' dollars to spend.<BR>'); document.write('You spend 50 dollars.<BR>'); money=50; document.write('You have '+money+' dollars to spend.'); </SCRIPT> </HEAD> </HTML> The <BR> tags demonstrate the close link between HTML and JavaScript. We can use JavaScript to write HTML to a web page, in this case we write <BR> to force a line-break, and neatly present the story. We can display string variables in a similar way. This program produces exactly the same output as the previous one. <HTML> <HEAD> <TITLE>Changing Variables 2</TITLE> <SCRIPT> money='100 dollars'; document.write('You have '+money+' to spend.<BR>'); money='50 dollars'; document.write('You spend '+money+'.<BR>You have '+money+' to spend.'); </SCRIPT> </HEAD> </HTML> But this is too simple, and it is also too clumsy. To model real life, we need more flexibility with our variables. We might not always spend 50 dollars - we might not even be American! This introduces the next section of JavaScript, the operator.

FUNCTIONS
A function will be executed by an event or by a call to the function.

JavaScript Functions
To keep the browser from executing a script when the page loads, you can put your script into a function. A function contains code that will be executed by an event or by a call to the function. You may call a function from anywhere within a page (or even from other pages if the function is embedded in an external .js file). Functions can be defined both in the <head> and in the <body> section of a document. However, to assure that a function is read/loaded by the browser before it is called, it could be wise to put functions in the <head> section.

How to Define a Function


Syntax
function functionname(var1,var2,...,varX) { some code }

The parameters var1, var2, etc. are variables or values passed into the function. The { and the } defines the start and end of the function. Note: A function with no parameters must include the parentheses () after the function name. Note: Do not forget about the importance of capitals in JavaScript! The word function must be written in lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a function with the exact same capitals as in the function name.

JavaScript Function Example


Example
<html> <head> <script type="text/javascript"> function displaymessage() { alert("Hello World!"); } </script> </head> <body> <form> <input type="button" value="Click me!" onclick="displaymessage()" /> </form> </body> </html>

Try it yourself

If the line: alert("Hello world!!") in the example above had not been put within a function, it would have been executed as soon as the page was loaded. Now, the script is not executed before a user hits the input button. The function displaymessage() will be executed if the input button is clicked. You will learn more about JavaScript events in the JS Events chapter.

The return Statement


The return statement is used to specify the value that is returned from the function. So, functions that are going to return a value must use the return statement. The example below returns the product of two numbers (a and b):

Example
<html> <head> <script type="text/javascript"> function product(a,b) { return a*b; } </script> </head> <body> <script type="text/javascript"> document.write(product(4,3)); </script> </body> </html>

Try it yourself

The Lifetime of JavaScript Variables


If you declare a variable, using "var", within a function, the variable can only be accessed within that function. When you exit the function, the variable is destroyed. These variables are called local variables. You can have local variables with the same name in different functions, because each is recognized only by the function in which it is declared. If you declare a variable outside a function, all the functions on your page can access it. The lifetime of these variables starts when they are declared, and ends when the page is closed.

DATA TYPES

Numbers - are values that can be processed and calculated. You don't enclose them in quotation marks. The numbers can be either positive or negative. Strings - are a series of letters and numbers enclosed in quotation marks. JavaScript uses the string literally; it doesn't process it. You'll use strings for text you want displayed or values you want passed along. Boolean (true/false) - lets you evaluate whether a condition meets or does not meet specified criteria.

Null - is an empty value. null is not the same as 0 -- 0 is a real, calculable number, whereas null is the absence of any value.
TYPE Numbers Strings Boolean Null EXAMPLE Any number, such as 17, 21, or 54e7 "Greetings!" or "Fun" Either true or false A special keyword for exactly that the null value (that is, nothing)

JavaScript Loops
Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this. In JavaScript, there are two different kind of loops:

for - loops through a block of code a specified number of times while - loops through a block of code while a specified condition is true

The for Loop


The for loop is used when you know in advance how many times the script should run.

Syntax
for (variable=startvalue;variable<=endvalue;variable=variable+increment) { code to be executed }

Example
The example below defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs. Note: The increment parameter could also be negative, and the <= could be any comparing statement.

Example
<html> <body> <script type="text/javascript"> var i=0; for (i=0;i<=5;i++) { document.write("The number is " + i); document.write("<br />"); } </script> </body> </html>

Try it yourself

The while Loop


The while loop loops through a block of code while a specified condition is true.

Syntax
while (variable<=endvalue) { code to be executed }

Note: The <= could be any comparing operator.

Example
The example below defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs:

Example
<html> <body> <script type="text/javascript"> var i=0; while (i<=5) { document.write("The number is " + i); document.write("<br />"); i++; } </script> </body> </html>

Try it yourself

The do...while Loop


The do...while loop is a variant of the while loop. This loop will execute the block of code ONCE, and then it will repeat the loop as long as the specified condition is true.

Syntax
do { code to be executed } while (variable<=endvalue);

Example
The example below uses a do...while loop. The do...while loop will always be executed at least once, even if the condition is false, because the statements are executed before the condition is tested:

Example
<html> <body> <script type="text/javascript"> var i=0; do { document.write("The number is " + i); document.write("<br />"); i++; } while (i<=5); </script> </body> </html>

Try it yourself

There is another combination of if statements where an alternative notation is available. We may need to test one variable for a number of different values and run different code depending on which of those values that it has. An example of the code to do this type of testing using if statements is shown here.

if ('a' == letter) { a += 1; } else if ('b' == letter) b += 1; } else if ('c' == letter) c += 1; } else if ('d' == letter) d += 1; } else if ('e' == letter) e += 1; } else if ('f' == letter) f += 1; } else { otherLetter += 1; }

{ { { { {

This combination comes up frequently in JavaScript. JavaScript provides a shorter and easier to read way of coding tests like this. This alternative construct is usually called a case statement because almost every programming language that provides it uses the word "case" to define the various values to be compared. In JavaScript the reserved word switch indicates the start of a case statement and each of the individual tests is identified with the reserved word case. A third reserved word break breaks out of the entire statement and jumps to the statement following the end of the switch block. Here is a part of our code from above rewritten to use a case statement in place of most of if statements.

switch (letter) { case 'a': a += case 'b': b += case 'c': c += case 'd': d += case 'e': e += case 'f': f += }

1; 1; 1; 1; 1; 1;

break; break; break; break; break; break;

Note that the last break statement is really redundant since the next statement is after the end of the block in any case but is best included for consistency and to allow additional cases to be easily added to the end of the statement. As with most JavaScript the actual way that you format the statement is up to you. All of the statements in these examples end with a semi-colon. The semi-colons to end each statement in JavaScript are optional provided that each statement is on a separate line. It is better to always including the semi-colons to make it clear where each statement ends. Where you have just a short statement to include within each case, including the break statement on the same line as the preceding statement allows us to fit each case on a single line making the entire switch statement much more readable.

You might also like