My Simple JavaScript Tutorial

 
Chapter 1. Introduction to JavaScript
  • What is JavaScript?
  • Is it Java or how it is related to Java?
  • What should I know to learn JavaScript?
  • What are the softwares I need to install for JavaScript?
  • Something more about JavaScript.
  • What is the basic structure of JavaScript?
  • Where to place my JavaScript in a HTML?
Chapter 2. Variables and Data Types
  • Variables
  • Assigning values to a variable
  • Simple Data Types
  • Special Data Types
  • Complex Data Types
  • Data Type Conversion
Chapter 3. Operators
  • Arithmetic Operators
  • Comparison Operators
  • Boolean Operators
  • Assignment Operators
  • Special Operators
Chapter 4. Statements
  • Conditional Statement: if ... else
  • Conditional Statement: switch
  • Loop: for
  • Loop: do ... while
  • Loop: while
  • break and continue
  • Single line comment and multiline comment
Chapter 5. Functions
  • Creating functions
  • Calling functions
Chapter 6. Event Handlers
 
Chapter 7. JavaScript in Action - Examples
What is JavaScript?

JavaScript is Netscape's cross-platform, object-based scripting language. It is not useful as a standalone language. It can be embed with a HTML file to give an interaction to the web pages. JavaScript can also be thought of as an extension to HTML. The JavaScript is interpreted by the client web browser and solve our purpose.

By using JavaScript, we can customize our web pages on the fly, write event handlers, validate data at the client-side and perform other client-side computation. JavaScript brings interaction to the web pages.

For example, when a user press the SUBMIT button in a html form, if we want to check the value of a mandatory text field, we no need make a server call for this purpose initially. If it is something simple, we can do the validation locally, ie., in the client-side itself using JavaScript and give an alert to the user asking him to enter a value in that field. JavaScript can also be used in a number of ways to spice up our page.

Now-a-days, almost all the web applications needs this type scripts, for various purpose. There are few scripts of this kind. The one more is VBScript by Microsoft. But JavaScript is one widely used. The advantage of JavaScript over other scripting languages of this kind will be explained in due course.

The current version of JavaScript is 1.5.

 
Is it Java or how it is related to Java?

JavaScript and Java are similar in some ways but fundamentally different in others. The JavaScript language resembles Java but does not have Java's static typing and strong type checking. JavaScript supports most Java expression syntax and basic control-flow constructs.

 
What should I know to learn JavaScript?

Some basic HTML is enough. The knowledge of any programming language, will make the understanding easier. But, it is not a must. Nothing to worry.

 
What are the softwares I need to install for JavaScript?
Nothing more than
  • a latest web browser which supports JavaScript. All most all the latest web browsers supports JavaScript. The minimum is Netscape 3 or IE4. (IE3.02 supports JavaScript but not all the functions will wok.) and
  • a basic text editor.
 
Something more about JavaScript.
  • JavaScript is case sensitive.
  • JavaScript is divided into two as client-side and server-side JavaScript.
  • Out of these two sections, only the client-side JavaScript is widely used.Even the server-side JavaScript having its own features, there are more popular and advanced server-side scripts, like Servlet, Java Server Page(JSP), Active Server Page (ASP), are available.
  • The scope of this document is to tell about client-side JavaScript.
 
What is the basic structure of JavaScript?
<SCRIPT language="JavaScript">

            ... JavaScript Code ...

</SCRIPT>

Also can also specify an external JavaScript file as,

<SCRIPT language="JavaScript" src="myJavaScript.js"></SCRIPT>
  • You can have as many <SCRIPT> tags as you like.
  • Close the first one before start the new one.

Where to place my JavaScript in a html?

Anywhere in the html. But the recommended place is inside the <HEAD> </HEAD> tags of your html. This way, your functions are loaded before the page begins to display, and you won't see all kinds of JavaScript errors.

Example:
<HTML>
<HEAD>
<TITLE>My Title</TITLE>
<SCRIPT language="JavaScript">
function cool() {
   .......
}
</SCRIPT>
</HEAD> 

Here, you may ask me, what will happen if suppose somebody use some old browsers? The answer is, if the old browser don't recognize the tag <SCRIPT> and rather than performing your JavaScript, they will display your script as text in the browser. OK. Then how to avoid this? See the following:

<SCRIPT language="JavaScript">
<!--  Hide from older browsers

	...... JavaScript Statements .......

// end hiding-->
</SCRIPT>

      Before start programming, we see some examples in the examples page.
                                
Variables

Variables are used for storing values. These values can be changed continually during the script execution. A variable name can consist of alphanumeric characters and the underscore. It cannot begin with a numeral. Variable names are case sensitive.

Valid variable names:

	myName
	my_name
	total
	 _total
	Average

Invalid variable names:

	100_numbers (starts with a numeral)
	rate%_of_inflation (illegal character)
Assigning values to a variable
	var yourName;  // undefined
	var message;   // undefined.
	var total = 5000;
	var ourSite = "www.programmersworld.biz";

We can also declare variable without specifing "var", ie, like

	yourName;
	message;
	total = 5000;
	ourSite = "www.programmersworld.biz";
Simple Data Types

There are three simple data types are in JavaScript:

  • Number : used for arithmetic operations Ex.: 10, 0.23, 12.234
  • String : used to handle text. Ex.: "Hello World", 'Hi friends', "19, Agraharam".
  • Boolean : used to perform logical operations. Ex.: true, false.

Special Data Types

There are two special data types are in JavaScript:

  • Null : used to represent where no value exists. Also a JavaScript keyword.
  • Undefined : used to represent where the value has not been defined. Also a JavaScript keyword.
Complex Data Types

There are three complex data types are in JavaScript:

  • Object : represents a collection of data and functions.
  • Array : stores a collection of data in the format of an array.
  • Function : a method or program.
We discuss about these complex data types in latter part of this guide.
 
Data Type Conversion

JavaScript is a dynamically typed language. ie., we need to specify the data type of a variable when we declare it, and data types are converted automatically as needed during script execution.

Example:

	var myBus = 857;

Later, we can assign a string value to this variable like,

	myBus = "This bus going to Yishun ..."

Because JavaScript is dynamically typed, this wouldn't cause an error.

Examples:

	x = "The answer is " + 42 // returns "The answer is 42"
	y = 42 + " is the answer" // returns "42 is the answer"

	    

In statements involving other operators, JavaScript does not convert numeric values to strings.

For example: "37" - 7 // returns 30 "37" + 7 // returns 377
Arithmetic Operators
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus: gives the remainder after division. Example 13 % 5 will return 3.
++ Unary increment:
This operator only takes one operand. The operand's value is increased by 1. The value returned depends on whether the ++ operator is placed before or after the operand; e.g. ++x will return the value of x following the increment whereas x++ will return the value of x prior to the increment.
-- Unary decrement:
This operator only takes one operand. The operand's value is decreased by 1. The value returned depends on whether the -- operator is placed before or after the operand; e.g. --x will return the value of x following the decrement whereas x-- will return the value of x prior to the decrement.
 
Comparison Operators
== "Equal to". Returns true if operands are equal.
!= "Not equal to". Returns true if operands are not equal.
> "Greater than". Returns true if left operand is greater than right operand.
>= "Greater than or equal to". Returns true if left operand is greater than or equal to right operand.
< "Less than". Returns true if left operand is less than right operand.
<= "Less than or equal to". Returns true if left operand is less than or equal to right operand.
 
Boolean Operators
&& "And". Returns true if both operands are true. Ex. ((3 < 4) && (6 > 5)). Here, since both cases are true, it will return true.
|| "Or". Returns true if either operand is true.
 
Assignment Operators
= Assigns the value of the righthand operand to the variable on the left.
Example:
maxVal = 100;
totalMark = (subjectOneMark + subjectTwoMark + subjectThreeMark);
+= Adds the righthand value with the lefthand value and stores total in the lefthand variable.
total += subjectOneMark;
[Also, -=, *=, /=]
 
Special Operators
  Conditional operator: (some condition) ? trueValue : falseValue

If a condition is true, assigns trueValue else, assigns the falseValue.

Example:

success = (subjectOneMark >= 50) ? true : false;
 
  typeof operand: Returns the data type of operand.

Example:

To test a variable's data type:

if (typeof totalMarks == "number") {
...
}

Statements define the flow of a program. Here we are going see conditional statements, loops and how to comment out a line or a block.

 
Conditional Statement: if ... else

As seen in many programming languages, based on a condition, it will execute if part or (optionally) else part.

	if (condition) {
		...
	} else {
		...
	}
Here, the else part is optional.
 
Conditional Statement: switch
The 'switch' statement is a shorthand of using many 'if' statements.
switch (expression) {
    case match1:
            ... statement1 ...
    break;

    case match2:
            ... statement2 ...
    break;

    case match3:
            ... statement3 ...
    break;

    default:
            ... default statement ..
}
Note: Look at the "break".
Use of this break is to avoid the execution of any cases below the matching case.
Use of the "default" is optional.
 
Loop: for
for (initial-statement; condition; increment) {

        ...statements ...

}
Loop: do ... while
do {
        ... statements ...
} while (condition)
Loop: while
while (condition) {
... statements ...
}
break and continue

Both of these statements are used to jumb out of an iterating loop.

break used to abort or come out of a loop.
continue used to abort a single iteration of a loop.

Example:

for (i = 0; i < 10; i++) {
    if (i == 5) {
        alert ("i == " + i);
        break;
    } else {
        continue;
    }
}
Comments

Comments can explain the action, like a color commentary, which can be a great help in understanding the code and debugging. Comments are optional for a program.

Example:
	// This is single line comment

	/*
	This
	is
	multiline
	comment.
	*/

A function is group of statements. Functions are the fundamental building blocks of any programming language.

There are two types of functions, builtin functions and user-defined functions.

toUpperCase(), substring() are the examples for builtin functions

Now, we start learn how to declare a function and make use of it.

 
Creating functions
Syntax to define a function:
function functionName(argument1, argument2, ...) {

        ... statements ...

}

Arguments are optional to a function.

Example: 1

function checkEntries(x, y) {
    if (x > y) {
            return true;
    } else {
            return false;
    }
}

Example: 2
function printErrorMessage() {
        document.write("Error:...");
}
Calling functions
We can call function
isValueOK = checkEntries(25, 40);

or

if (checkEntires(25, 40)) {
    ....
} else {
    printErrorMessage();
}

In JavaScript, mostly the functions are called inside an event handler. Next lets see about event handlers.

Find JavaScript Examples here.