Javascript Introduction

What is Javascript?
Javascript is the programming language of the web. It is an interpreted programming language, which means that a programme is not compiled into executable machine code until it is run. It is a scripting language which basically means that it interacts with other functions or programs and is written in a language that is close to English. The required interpreter for Javascript code is incorporated into many (but not all) of the more common web-browsers (e.g. Internet Explorer) making it one of the most popular client-side web-programming languages.
What can it do?
Javascript can and is used to perform many tasks in web-design. Common examples include:

  • Javascript Rollovers: Changing an image (e.g. a button) as a user rolls their mouse over the image;
  • Test and verification of user input and selections in form elements;
  • Manipulation of elements in the browser window. E.g. Animating text or graphics – DHTML.;
  • Controlling the behaviour of a browser. E.g. Opening and closing browser windows with or without various elements (e.g. toolbars, scrollbars, resize facilities etc.);
  • Present advisory messages to a user;
  • Browser Type and Version Detection
  • And much, much more…
What can Javascript not do?
Javascript cannot

  1. Manipulate files and directories on a users computer.
  2. Produce graphics (except by using HTML elements).
  3. Support networking.
How does it relate to Java?
Javascript is not Java. Originally the language was called Livescript but the name was changed for marketing purposes, and it worked. By using the name Javascript people have come to believe that it is a simplified version of the Java programming language developed by Sun MIcrosystems – which is not true.
What are the differences between Client-Side and Server-Side Javascript?
The combination of a Javascript Interpreter with a Web Browser provides support for client-side Javascript, which is Javascript code that will be interpreted and run from the users computer. Server-side scripts will have been interpreted before a web page is sent to the client.
This all sounds very technical – is it hard to learn?
The best way to learn any new language (French, German, C#, Visual Basic etc.) is to use it. Javascript is a high level programming language which means it’s written in words that are pretty close to english, most of the time. It also requires no special tools, unlike compiled languages, since Javascript support is incorporated into many of the most popular Web Browser programs (e.g. Netscape; Internet Explorer). It is not easy to learn. But it is fun, and there are mountains of freely available scripts available so you may find you never need to actually write any of your own. The ability to understand, adapt and combine freely available scripts is obviously a useful skill for a web-developer to have.
Are there any recommended books on Javascript?
I try to avoid recommending books if there is an abundance of information freely available on the net, which there is for HTML and XHTML. The same applies to Javascript. All you need to know is freely available on the net. However, there are a number of excellent books on the subject, my favorite being: ‘Javascript. The Definitive Guide.’ By David Flanagan from O’Reilly. There is an online version of this book at this location: Javascript: Definitive Guide. At the following site you will find a another freely available e-book on the Javascript language: Netscape: Javascript Central.

I’ve also provided some links (to the left) to a variety of Javascript tutorials that you are encouraged to visit.

Exercise

There are an abundance of freely available javascripts that you can download and use in your pages. You may never need to write your own, but it is useful to have an understanding of how javascript works – and that’s coming next.

In this exercise you will have a go at downloading one or more javascript examples and incorporating them into your pages.

Pay a visit to this excellent javascript resource site: JavascriptKit.com.

There are many categories to choose from. To start with have a go at a simple calculator. The javascript and an example can be found here: Simple Calculator. You will notice that there are some form elements and that the HTML is written in uppercase. Remember to convert this if you intend to keep the calculator code in your pages.

If you have problems here is a copy that I made earlier: My Basic Calculator

Now have a go at a javascript that produces text effects. I’ll leave it up to you to choose one. Here’s one that I prepared earlier…: Rainbow Heading.

Javascript Syntax

Lets get right down to it and learn some of the basics of the language.

How to Insert Javascript into HTML Pages

Javascript is added to an HTML (or XHTML) page using the <script> tag introduced last week. It may be placed in the body or the head sections of a page or it may be referenced from an external file, it depends upon the function of the code. The code that is written between the <script> tags should also be enclosed in a pair of comment tags (<!– and –>). The closing comment tag is generally preceded by a Javascript comment-line indicator which is 2 slashes. E.g.

	<script type="text/javascript" language="javascript">
	<!--
	(Javascript code goes here...)
	//-->
	</script>
	

This is the standard way for adding Javascript to your pages so that it works with browsers that are Javascript enabled, but ignored by those that do not support Javascript.

The ‘type’ and ‘language’ Attributes

If you take a look at the details of the <script> tag you will have discovered that the ‘language’ attribute of the <script> tag is not supported in XHTML1.0 strict. Instead it is replaced by the ‘type’ attribute. It is quite common to find them both used simultaneously to try and ensure that the viewing browser is aware of the language that the script is written in. It is also common to find a meta tag used for the same purpose. E.g.

	<meta http-equiv="Content-Script-Type"
	content="text/javascript">

Syntax – Conventions

All languages have rules and conventions. The English language requires that each sentence starts with a capital letter, ends with a full stop, contains a subject and at least one verb. Programming languages have similar rules.

Case Sensitivity
Javascript is case sensitive. This means that it will treat the following terms differently:

  • variable & Variable;
  • onmousedown & OnMousedown;
  • myname & myName;

You should also maintain your awareness of the case requirements for XHTML compliance: All attribute names must be in lower case.

Semicolons
All Javascript statements should end with a semi colon. Semi-colons are used to separate Javascript statements. For example: var x=10; var y=20; is two Javascript statements.
White Space
Javascript is insensitive to white space, tabs or new lines within a statement. It will, however, recognise spaces, tabs and new lines if they ar part of a string. (More on strings in due course).

E.g. var x=0; is the same as: var x = 0;

It is good practice to use spacing in your code to make it more readable. It is bad programming practice to let statements span multiple lines.

Strings and Quotes
A string is a sequence of zero or more characters enclosed between quotation marks (either single or double). As a rule, single quote marks are used to delimit strings that contain double quotes.

E.g. ‘She said “Time for tea”‘

The single quotation mark may be used within strings delimited by double marks.

E.g. onclick=”window.alert(‘I was clicked’);”

In this example the ‘onclick’ attribute must have its value enclosed within quotation marks to meet the requirements of XHTML, and the string to be displayed is enclosed within single quotes to meet the syntax requirements of Javascript. Here’s another:

<input type="button" value="panic"
onclick="window.alert('emergency');">

In the code snippet above we have our familiar <input> tag with its attribute values enclosed within double quotation marks, as required for XHTML compliance. The actual alert box message is therefore enclosed within single quotes.

The Backslash Character (\)
The backslash has special pupose in Javascript strings. It is followed by another character and together they represent something that cannot be typed at the Keyboard.
E.g. \n is used to cause a line feed and carriage return.

These backslash and letter combinations are generally referred to as Escape Sequences
The backslash character is used to ‘escape from’ the usual meaning of the caharacter that follows it. It can be used to place single instances of quotes in a string:

'You\'re all doing very well...'

If the backslash had not preceded the apostrophe it would have been interpreted as the end of the string. Other escape sequences include:

  1. \n = New Line
  2. \b = Back Space
  3. \t = Horizontal Tab
  4. \v = Vertical Tab
  5. \f = Form Feed
  6. \r = Carriage Return
  7. \” = Double Quote
  8. \’ = Apostrophe

Exercise

Open this little page in which I have implemented a Javascript alert box: Alert Box Example.

Take a close look at the page code. You should see the following between the <script> tags in the head of the page:

	alert("Some text and escape sequences")

Alert boxes are used to provide a visitor with an important message.

Notice the use of the <noscript> tag in the body of the page. Take a trip to our friends at W3Schools to find out what the <noscript> tag is for: W3Schools on <noscript>.

Here is another example. This little snippet produces a prompt box. This dialogue box requires input from the user: Prompt Box

Take a copy of the code and:

  1. Change the message that the visitor is prompted with and
  2. Change the default text that appears in the prompt window.

Here is a 3rd example. This example presents a ‘confirm’ box to the user. You will have all encountered one of these before now. They usually say something like ‘Are you sure that you want to proceed’ and give 2 options, either yes or no. Here is an example that opens a confirm box in response to either a button click or a hyperlink click: Confirm and Alert.

Opening and Closing Brackets
All brackets must be used in pairs. That means that all brackets opened, must be closed.

Curly braces are used to enclose multiple Javascript statements.

Square brackets are used with a special data structure called Arrays.

And curved brackets are used to enclose functions or a method’s arguments. Much more on this in due course.

Comments in Javascript
A single line comment in Javascript code can be preceded by the double slash (//) which we saw used with the XHTML closing comment tag. Multiple line comments are enclosed between /* and */ (just like CSS comments).
Variable and Function Names
As the developer you get to choose the words used for your variables and functions. Your choices of names must follow these rules:

  1. The first character must be a letter or an underscore character;
  2. You must not use a number as the first character;
  3. There must be no spaces;
  4. You must not use any of the Javascript reserved words.

Exercise

Investigate Javascript reserved words at the following locations: Devedge on Keywords or Definitive Guide.

Basic Javascript Programming Constructs

Now that you have a grasp of the basic conventions of the Javascript language we can look at some of the basic programming constructs. Because Javascript is modeled on Java, which is, in turn, modeled on C and C++, much of this will be familiar to those who have previous experience with these languages.

Variables

A variable is simply a name associated with a value. The name can be thought of as a label on some space in the computers memory where data will be stored. Before a variable can be used in a Javascript program its name must be declared. Variables are declared using the var keyword as follows:

	var x;
	var y;
	var total;

These 3 declarations could be combined into one shorthand declaration as follows:


	var x, y, total;

It is also possible to carry out both declaration and initialisation of variables simultaneously.

	var x = 1, y = 10, total = 0;

This line declares 3 x variable names (x, y and total) and initialises them to their assigned values.

Variable Typing

A big differenced between Javascript and languages such as C++ is that Javascript is ‘untyped’. This means that a variable (remember that is a name for a value stored in memory) can hold any type of data. Unlike C or Java wherein variables are designated as specific types. This means that a variable in Javascript may, at one point, hold a numeric value and at another may be used to contain a string, or other data type.

Variable Scope

The scope of a variable is the area of a program where that variable is defined. Variables can have global or local scope. A global variable is defined and usable everywhere in your program. Local variables are declared within a function and are available only within the body of that function, not throughout the whole program.

Exercise

Visit our good friends at W3Schools and complete their little Javascript VAriables tutorial: W3Schools on Javascript Variables.

Revisit my little prompt box example and determine the word used for the variable that is used to hold the string entered by the user.

Operators

Operators are the things that act on variables. They include the assignment operator (= sign) which is used to assign a value to a variable; and the addition operator (+ sign) that is used to sum values. E.g.

	var x = 1, y = 10, total = 0;
	total = x + y;

This code snippet declares 3 x variables named, x, y and total. They are each initialised to specified numeric values using the assignment operator. Then the second line uses the summation operator (+) to add together the values of x and y and assign the sum to the variable ‘total’.

There are a range of operators in Javascript, as there are in all programming languages. Some are concerned with comparison. E.g. ‘==’ is the equality operator used to test for equality and ‘>’ is the greater than operator.

	var x = 1, y = 10, total = 0;
	if (total == 0)
	{total = x + y;}

This code snippet first declares and initilises our 3 variables. Then total is tested using the equality operator to see if it is ’0′. If it is 0 then the code between the curly braces is executed and total is assigned the value of x added to y.

The ‘if’ statement in this snippet is your first example of a control structure in Javascript.

Exercise

Now revisit our W3Schools friends and carry out their Operators Tutorial: W3Schools on Javascript Operators.

Expressions

An expression is a Javascript phrase that can be evaluated to produce a value. The simplest form of expression is the literal wherein the value of the literal expression is the literal value itself. E.g.


	4.5 = Numeric Literal
	"Monday" = String Literal

More complex expressions are created by combining simple expressions with operators. E.g.

	(x + 10) = Value determined by adding the
			two literal expressions combined
			by an operator (+).

Note: Remember to take a look at the tutorial links in the left hand menu for alternative explanations of these concepts.

Control Structures

Branches

The ‘if’ statement is a fundamental Javascript control element that enables Javascript to execute statements conditionally. E.g.

	if ((x==1) && (y==5)) {
		total = y-x;
		}

The form of this construct is:

	if (expression)
		{statement}

The example says: If the variable ‘x’ is equal to 1 and (&&) the variable ‘y’ is equal to 5 carry out the following statement. The following statement says: subtract the value of x from the value of y and assign the result to the variable ‘total’.

Make sure that you clearly understand what is taking place here, how the parentheses are used etc. as this is a fundamental construct that you will encounter often.

A variation of this control structure includes an else clause that is executed if the expression is false. The syntax is:

	if (expression)
		{statement}
	else
		{statement}

An ‘if’ statement can cause a branch in the flow of a program and multiple ‘if’ statements might be combined if multiple possible branching options are required. If the branching is dependent upon the condition of 1 variable it would be wasteful to repeatedly test the condition of that variable using if statements. The switch statement is provided for precisely this purpose. Using the ‘switch’ construct makes the code shorter and easier to read than a whole bunch of ‘if’ statements.

EXERCISE

Open this little example of the ‘switch’ statement in use: Javascript Switch. This is an expanded copy of the ‘switch’ example from the W3Schools site.

Study the code and research / answer the following:

  1. What is the function of the ‘case’ clauses in the switch construct?
  2. What is the function of the break statements?

Pay a visit to W3Schools and complete their Javascript Conditional Statements tutorial: W3Schools on Javascript Conditional Statements.

Loops

A loop is a common programming construct wherein the statements within the loop are repeatedly executed until a defined condition is met, at which point the looping ends.

While Loops

While loops are used when you don’t know how many times the loop will be executed. It enables repeated actions to be carried out. Consider the following code snippet:

	var x = 0;
	while ( x <= 10 ){ //Loop until x is greater than 10
		x++; //Increment x
		}

This snippet says: Initialise a variable called x to the number ’0′. While x is less than or equal to 10 increment x. This code will be executed 10 times, until x has been incremented (by the increment (++) operator) to 10.

Do/While Loops

This type of loop construct is similar to the ‘while’ loop but the loop expression is tested at the end of the loop code instead of the start. This ensures that the body of the loop code is always executed at least once. The basic syntax is as follows:

	do
		statement
	while
		(condition)

For Loops

Most loops employ a counter variable to count the number of times the loop has been executed. This variable is initilised before the loops starts and is tested before each pass through the loop and then incremented before being tested again. The for loop brings together these 3 actions: initialisation, test and increment. The general syntax of a for loop is:

	for (initialise; test; increment)
		statement

An example:

	for(var x = 0; x<=10; x++)
	document.write(x);

This example shows that for loops are easier to read and less error prone. It says: Initialise a variable called x to 0. While x is less than or equal to 10 write the value of x.

Exercise

Pay a visit to W3Schools and complete their Javascript Looping tutorial: W3Schools on Javascript Looping.

Leave a Comment