C++ Java Python JavaScript Physics Robotics Electronics Astronomy Summer Courses Other Courses

 

JavaScript Manual

 A Short History 
  What is JavaScript   Placement in HTML    Logical Operators   do while loop 
  JavaScript Syntax  Data Types   Assignment Operators   break Statement 
 First Script   Variables   if Statement   continue Statement 
  Whitespace and Linebreaks  Reserved Words   if else Statement   Function Definition 
  Case Sensitivity  Arithmetic Operators   switch Statement   Calling a Function 
  Comments  Comparison Operators   while Loop   Prompt Dialog Box 

  What is JavaScript?

JavaScript is:

JavaScript Syntax:

A JavaScript consists of JavaScript statements that are placed within the <script>... </script> HTML tags in a web page.

You can place the <script> tag containing your JavaScript anywhere within you web page but it is preferred way to keep it within the <head> tags.

The <script> tag alert the browser program to begin interpreting all the text between these tags as a script. So simple syntax of your JavaScript will be as follows

<script ...>
  JavaScript code
</script>

The script tag takes two important attributes:

So your JavaScript segment will look like:

<script language="javascript" type="text/javascript">
  JavaScript code
</script>

Your First JavaScript Script:

Let us write our class example to print out "Hello World".

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

Above code will display following result:

Hello World!

Whitespace and Line Breaks:

JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs.

Because you can use spaces, tabs, and newlines freely in your program so you are free to format and indent your programs in a neat and consistent way that makes the code easy to read and understand.

Semicolons are Optional:

Simple statements in JavaScript are generally followed by a semicolon character, just as they are in C, C++, and Java. JavaScript, however, allows you to omit this semicolon if your statements are each placed on a separate line. For example, the following code could be written without semicolons

<script language="javascript" type="text/javascript">
<!--
  var1 = 10
  var2 = 20
//-->
</script>

But when formatted in a single line as follows, the semicolons are required:

<script language="javascript" type="text/javascript">
<!--
  var1 = 10; var2 = 20;
//-->
</script>

Note: It is a good programming practice to use semicolons.

Case Sensitivity:

JavaScript is a case-sensitive language. This means that language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters.

So identifiers Time, TIme and TIME will have different meanings in JavaScript.

NOTE: Care should be taken while writing your variable and function names in JavaScript.

Comments in JavaScript:

JavaScript supports both C-style and C++-style comments, Thus:

JavaScript Placement in HTML File:

There is a flexibility given to include JavaScript code anywhere in an HTML document. But there are following most preferred ways to include JavaScript in your HTML file.

JavaScript DataTypes:

JavaScript allows you to work with three primitive data types:

JavaScript also defines two trivial data types, null and undefined, each of which defines only a single value.

JavaScript Variables:

Like many other programming languages, JavaScript has variables. Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container.

Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword as follows:

<script type="text/javascript">
<!--
var money;
var name;
//-->
</script>

JavaScript Variable Scope:

The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only two scopes.

JavaScript Variable Names:

While naming your variables in JavaScript keep following rules in mind.

JavaScript Reserved Words:

The following are reserved words in JavaScript. They cannot be used as JavaScript variables, functions, methods, loop labels, or any object names.

abstract
boolean
break
byte
case
catch
char
class
const
continue
debugger
default
delete
do
double
else
enum
export
extends
false
final
finally
float
for
function
goto
if
implements
import
in
instanceof
int
interface
long
native
new
null
package
private
protected
public
return
short
static
super
switch
synchronized
this
throw
throws
transient
true
try
typeof
var
void
volatile
while
with

The Arithmatic Operators:

There are following arithmatic operators supported by JavaScript language:

Assume variable A holds 10 and variable B holds 20 then:

Operator Description Example
+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiply both operands A * B will give 200
/ Divide numerator by denumerator B / A will give 2
% Modulus Operator and remainder of after an integer division B % A will give 0
++ Increment operator, increases integer value by one A++ will give 11
-- Decrement operator, decreases integer value by one A-- will give 9

The Comparison Operators:

There are following comparison operators supported by JavaScript language

Assume variable A holds 10 and variable B holds 20 then:

Operator Description Example
== Checks if the value of two operands are equal or not, if yes then condition becomes true. (A == B) is not true.
!= Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true.
> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true.
< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true.
<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true.

The Logical Operators:

There are following logical operators supported by JavaScript language

Assume variable A holds 10 and variable B holds 20 then:

Operator Description Example
&& Called Logical AND operator. If both the operands are non zero then then condition becomes true. (A && B) is true.
|| Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true. (A || B) is true.
! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A && B) is false.

The Assignment Operators:

There are following assignment operators supported by JavaScript language:

Operator Description Example
= Simple assignment operator, Assigns values from right side operands to left side operand C = A + B will assigne value of A + B into C
+= Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand C += A is equivalent to C = C + A
-= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand C -= A is equivalent to C = C - A
*= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand C *= A is equivalent to C = C * A
/= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand C /= A is equivalent to C = C / A
%= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand C %= A is equivalent to C = C % A

true or false based on the evaluation.

if statement:

The if statement is the fundamental control statement that allows JavaScript to make decisions and execute statements conditionally.

Syntax:

if (expression){
   Statement(s) to be executed if expression is true
}

if...else statement:

The if...else statement is the next form of control statement that allows JavaScript to execute statements in more controlled way.

Syntax:

if (expression)
{
   Statement(s) to be executed if expression is true
}else
{
   Statement(s) to be executed if expression is false
}

if...else if... statement:

The if...else if... statement is the one level advance form of control statement that allows JavaScript to make correct decision out of several conditions.

Syntax:

if (expression 1)
{
   Statement(s) to be executed if expression 1 is true
}
else if (expression 2)
{
   Statement(s) to be executed if expression 2 is true
}else if (expression 3)
{
   Statement(s) to be executed if expression 3 is true
}else
{
   Statement(s) to be executed if no expression is true
}

switch statement:

The basic syntax of the switch statement is to give an expression to evaluate and several different statements to execute based on the value of the expression. The interpreter checks each case against the value of the expression until a match is found. If nothing matches, a default condition will be used.

switch (expression)
{
  case condition 1: statement(s)
                    break;
  case condition 2: statement(s)
                    break;
   ...
  case condition n: statement(s)
                    break;
  default: statement(s)
}

The while Loop

The most basic loop in JavaScript is the while loop which would be discussed in this tutorial.

Syntax:

while (expression)
{
   Statement(s) to be executed if expression is true
}

The do...while Loop:

The do...while loop is similar to the while loop except that the condition check happens at the end of the loop. This means that the loop will always be executed at least once, even if the condition is false.

Syntax:

do
{
   Statement(s) to be executed;
} while (expression);

The for Loop

The for loop is the most compact form of looping and includes the following three important parts:

You can put all the three parts in a single line separated by a semicolon.

Syntax:

for (initialization; test condition; iteration statement)
{
     Statement(s) to be executed if test condition is true
}

The break Statement:

The break statement, which was briefly introduced with the switch statement, is used to exit a loop early, breaking out of the enclosing curly braces.

The continue Statement:

The continue statement tells the interpreter to immediately start the next iteration of the loop and skip remaining code block.

When a continue statement is encountered, program flow will move to the loop check expression immediately and if condition remain true then it start next iteration otherwise control comes out of the loop.

Function Definition:

Before we use a function we need to define that function. The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces. The basic syntax is shown here:

<script type="text/javascript">
<!--
function functionname(parameter-list)
{
  statements
}
//-->
</script>

Calling a Function:

To invoke a function somewhere later in the script, you would simple need to write the name of that function as follows:

<script type="text/javascript">

<!--
sayHello();
//-->
</script>

Exceptions

Exceptions can be handled with the common try/catch/finally block structure.

<script type="text/javascript">
<!--
try {
   statementsToTry
} catch ( e ) {
      catchStatements
} finally {
      finallyStatements
}
//-->
</script>

The try block must be followed by either exactly one catch block or one finally block (or one of both). When an exception occurs in the catch block, the exception is placed in e and the catch block is executed. The finally block executes unconditionally after try/catch.

Prompt Dialog Box:

You can use prompt dialog box as follows:

<head>
<script type="text/javascript">
<!--
   var retVal = prompt("Enter your name : ", "your name here");
   alert("You have entered : " +  retVal );
//-->
</script>
</head>