JavaScript-1
JavaScript-1
Al-Khwarizmi Institute of
Computer Science (KICS)
Office: +92-42-9250245 | Fax: +92-42-9250246
Al-Khawarizmi Institute of Computer Science
(KICS) UET, Lahore
http://www.kics.edu.pk
About the Tutorial
JavaScript is a lightweight, interpreted programming language. It is designed for creating
network-centric applications. It is complimentary to and integrated with Java. JavaScript is
very easy to implement because it is integrated with HTML. It is open and cross-platform.
Audience
This tutorial has been prepared for JavaScript beginners to help them understand the
basic functionality of JavaScript to build dynamic web pages and web applications.
Prerequisites
For this tutorial, it is assumed that the reader have a prior knowledge of HTML coding. It
would help if the reader had some prior exposure to object-oriented programming concepts
and a general idea on creating online applications.
Table of Contents
About the Tutorial ................................................................................................................ iii
Audience............................................................................................................................... iii
Prerequisites ......................................................................................................................... iii
2. JavaScript ............................................................... 2
What is JavaScript? ................................................................................................................ 2
Client-Side JavaScript ............................................................................................................ 2
Advantages of JavaScript ....................................................................................................... 2
Limitations of JavaScript ....................................................................................................... 3
JavaScript Development Tools............................................................................................... 3
3. Syntax...................................................................... 4
JavaScript Outputs.................................................................................................................. 4
Your First JavaScript Code .................................................................................................... 4
Comments in JavaScript ......................................................................................................... 5
4. Variables ................................................................. 6
JavaScript Datatypes .............................................................................................................. 6
JavaScript Variables ............................................................................................................... 6
JavaScript Variable Scope ...................................................................................................... 7
JavaScript Variable Names .................................................................................................... 8
JavaScript Reserved Words .................................................................................................... 8
6. Functions............................................................... 14
Function Definition .............................................................................................................. 14
Syntax .............................................................................................................................. 14
Calling a Function ................................................................................................................ 14
Function Parameters ............................................................................................................. 15
The return Statement ............................................................................................................ 16
Nested Functions .................................................................................................................. 17
Function () Constructor ........................................................................................................ 18
Function Literals .................................................................................................................. 19
7. OPERATORS ....................................................... 22
What is an Operator? ............................................................................................................ 22
Arithmetic Operators ............................................................................................................ 22
Comparison Operators.......................................................................................................... 23
Logical Operators ................................................................................................................. 25
Bitwise Operators ................................................................................................................. 26
Assignment Operators .......................................................................................................... 27
Miscellaneous Operators ...................................................................................................... 29
Conditional Operator (? :) ................................................................................................ 29
typeof Operator ................................................................................................................ 30
8. SWITCH-CASE ................................................... 31
Flow Chart ............................................................................................................................ 31
Syntax ................................................................................................................................... 31
2. JavaScript
What is JavaScript?
Javascript is a dynamic computer programming language. It is lightweight and most
commonly used as a part of web pages, whose implementations allow client-side script to
interact with the user and make dynamic pages. It is an interpreted programming language
with object-oriented capabilities.
JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript,
possibly because of the excitement being generated by Java. JavaScript made its first
appearance in Netscape 2.0 in 1995 with the name LiveScript. The general-purpose
core of the language has been embedded in Netscape, Internet Explorer, and other web
browsers.
The ECMA-262 Specification defined a standard version of the core JavaScript language.
• JavaScript is a lightweight, interpreted programming language.
• Designed for creating network-centric applications.
• Complementary to and integrated with Java.
• Complementary to and integrated with HTML.
• Open and cross-platform.
Client-Side JavaScript
Client-side JavaScript is the most common form of the language. The script should be
included in or referenced by an HTML document for the code to be interpreted by the
browser.
It means that a web page need not be a static HTML, but can include programs that interact
with the user, control the browser, and dynamically create HTML content.
The JavaScript client-side mechanism provides many advantages over traditional CGI server-
side scripts. For example, you might use JavaScript to check if the user has entered a valid e-
mail address in a form field.
The JavaScript code is executed when the user submits the form, and only if all the entries are
valid, they would be submitted to the Web Server.
JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and
other actions that the user initiates explicitly or implicitly.
Advantages of JavaScript
The merits of using JavaScript are:
• Less server interaction: You can validate user input before sending the page off to the
server. This saves server traffic, which means less load on your server.
• Immediate feedback to the visitors: They don't have to wait for a page reload to see if
they have forgotten to enter something.
JavaScript [3]
• Increased interactivity: You can create interfaces that react when the user hovers over
them with a mouse or activates them via the keyboard.
• Richer interfaces: You can use JavaScript to include such items as drag- and-drop
components and sliders to give a Rich Interface to your site visitors.
Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It lacks the following
important features:
• Client-side JavaScript does not allow the reading or writing of files. This has been
kept for security reason.
• JavaScript cannot be used for networking applications because there is no such
support available.
• JavaScript doesn't have any multithreading or multiprocessor capabilities. Once again,
JavaScript is a lightweight, interpreted programming language that
allows you to build interactivity into otherwise static HTML pages.
3. Syntax
JavaScript can be implemented using JavaScript statements that are placed within the
<script>... </script> HTML tags in a web page.
You can place the <script> tags, containing your JavaScript, anywhere within you web page,
but it is normally recommended that you should keep it within the <head> tags.
The <script> tag alerts the browser program to start interpreting all the text between these
tags as a script. A simple syntax of your JavaScript will appear as follows.
JavaScript Outputs
JavaScript can "display" data in different ways:
Writing into an alert box, using window.alert().
Writing into the HTML output using document.write().
Writing into an HTML element, using innerHTML.
Writing into the browser console, using console.log().
<html>
<body>
<script language="javascript" type="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>
Syntax [5]
Result
Comments in JavaScript
JavaScript supports both C-style and C++-style comments. Thus:
Any text between a // and the end of a line is treated as a comment and is ignored by
JavaScript.
Any text between the characters /* and */ is treated as a comment. This may span
multiple lines.
JavaScript also recognizes the HTML comment opening sequence <!--.
JavaScript treats this as a single-line comment, just as it does the //
comment.
The HTML comment closing sequence --> is not recognized by JavaScript so it
should be written as //-->.
Example
The following example shows how to use comments in JavaScript.
4. Variables
JavaScript Datatypes
One of the most fundamental characteristics of a programming language is the set of data
types it supports. These are the type of values that can be represented and manipulated in a
programming language.
JavaScript allows you to work with three primitive data types:
• Numbers, e.g., 123, 120.50 etc.
• Strings of text, e.g. "This text string" etc.
• Boolean, e.g. true or false.
JavaScript also defines two trivial data types, null and undefined, each of which defines
only a single value. In addition to these primitive data types, JavaScript supports a composite
data type known as object. We will cover objects in detail in a separate chapter.
Note: Java does not make a distinction between integer values and floating- point values. All
numbers in JavaScript are represented as floating-point values. JavaScript represents numbers
using the 64-bit floating-point format defined by the IEEE 754 standard.
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>
You can also declare multiple variables with the same var keyword as
follows:
<script type="text/javascript">
<!--
var money, name;
//-->
</script>
Storing a value in a variable is called variable initialization. You can do variable initialization
at the time of variable creation or at a later point in time when you need that variable.
For instance, you might create a variable named money and assign the value
2000.50 to it later. For another variable, you can assign a value at the time of initialization as
follows.\
Variables [7]
Example
<script type="text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script>
Note: Use the var keyword only for declaration or initialization, once for the life of any
variable name in a document. You should not re-declare same variable twice.
JavaScript is untyped language. This means that a JavaScript variable can hold a value of any
data type. Unlike many other languages, you don't have to tell JavaScript during variable
declaration what type of value the variable will hold. The value type of a variable can change
during the execution of a program and JavaScript takes care of it automatically.
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
}
document.write(myVar);//if function will call then result will
local
</script>
</head>
<body>
</body>
Variables [8]
</html>
Result:
5. Objects In JavaScript
JavaScript is an Object Oriented Programming (OOP) language. A programming language
can be called object-oriented if it provides four basic capabilities to developers:
• Encapsulation: the capability to store related information, whether data or methods,
together in an object.
• Aggregation: the capability to store one object inside another object.
• Inheritance: the capability of a class to rely upon another class (or number of classes)
for some of its properties and methods.
• Polymorphism: the capability to write one function or method that works in a variety
of different ways.
Objects are composed of attributes. If an attribute contains a function, it is considered to be a
method of the object, otherwise the attribute is considered a property.
Object Properties
Object properties can be any of the three primitive data types, or any of the abstract data
types, such as another object. Object properties are usually variables that are used internally
in the object's methods, but can also be globally visible variables that are used throughout the
page.
The syntax for adding a property to an object is:
objectName.objectProperty = propertyValue;
For example: The following code gets the document title using the "title" property of the
document object.
Object Methods
Methods are the functions that let the object do something or let something be done to it.
There is a small difference between a function and a method – at a function is a standalone
unit of statements and a method is attached to an object and can be referenced by the this
keyword.
Methods are useful for everything from displaying the contents of the object to the screen to
performing complex mathematical operations on a group of local properties and parameters.
For example: Following is a simple example to show how to use the
write() method of document object to write any content on the document.
document.write ("This is test");
Objects In JavaScript [10]
User-Defined Objects
All user-defined objects and built-in objects are descendants of an object called
Object.
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
var book = new Object(); // Create the object book.subject
= "Perl"; // Assign properties to the object
book.author = "Mohtashim";
</script>
</head>
<body>
<script type="text/javascript">
document.write("Book name is : " + book.subject + "<br>");
document.write("Book author is : " + book.author + "<br>");
</script>
</body>
</html>
Result
Objects In JavaScript [11]
Example 2
This example demonstrates how to create an object with a User-Defined Function.
Here this keyword is used to refer to the object that has been passed to a function.
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
function book(title, author) {
this.title = title;
this.author = author;
}
</script>
</head>
<body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author +
"<br>");
</script>
</body>
</html>
Result
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
// Define a function which will work as a method
function addPrice(amount) {
this.price = amount;
Objects In JavaScript [12]
}
function book(title, author) {
this.title = title; this.author = author;
this.addPrice = addPrice; // Assign that method as
property.
}
</script>
</head>
<body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>
Result
Syntax
The syntax for with object is as follows:
with (object){
properties used without the object name and dot
}
Example
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
// Define a function which will work as a method
Objects In JavaScript [13]
function addPrice(amount) {
with (this) {
price = amount;
}
}
function book(title, author) {
this.title = title; this.author = author; this.price =
0;
this.addPrice = addPrice; // Assign that method as
property.
}
</script>
</head>
<body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>
Result
Functions [14]
6. Functions
A function is a group of reusable code which can be called anywhere in your program. This
eliminates the need of writing the same code again and again. It helps programmers in writing
modular codes. Functions allow a programmer to divide a big program into a number of small
and manageable functions.
Like any other advanced programming language, JavaScript also supports all the features
necessary to write modular code using functions. You must have seen functions like alert()
and write() in the earlier chapters. We were using these functions again and again, but they
had been written in core JavaScript only once.
JavaScript allows us to write our own functions as well. This section explains how to write
your own functions in JavaScript.
Function Definition
Before we use a function, we need to define it. 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.
Syntax
The basic syntax is shown here.
<script type="text/javascript">
function functionname(parameterlist)
{
statements
}
</script>
Example
Try the following example. It defines a function called sayHello that takes no parameters:
<!DOCTYPE html>
<html>
<head>
<title>Funcations</title>
<script type="text/javascript">
function sayHello() {
alert("Hello there");
}
</script>
</head>
<body>
<p>JavaScriot funcations</p>
</body>
</html>
Calling a Function
To invoke a function somewhere later in the script, you would simply need to write the name
of that function as shown in the following code.
Functions [15]
<html>
<head>
<script type="text/javascript">
function sayHello() {
document.write("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello()" value="Say
Hello">
</form>
<p>Use different text in write method and then try...</p>
</body>
</html>
Output (before Click):
Function Parameters
Till now, we have seen functions without parameters. But there is a facility to pass different
parameters while calling a function. These passed parameters can be captured inside the
function and any manipulation can be done over those parameters. A function can take
multiple parameters separated by comma.
Example
Try the following example. We have modified our sayHello function here. Now it takes two
parameters.
<html>
<head>
<title>Function Parameters</title>
<script type="text/javascript">
function sayHello(name, age) {
document.write(name + " is " + age + " years old.");
}
Functions [16]
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello('Saqib Nazir', 24)"
value="Say Hello">
</form>
<p>Use different parameters inside the function and then
try...</p>
</body>
</html>
Output (Before Click):
Output(After click):
document.write(result);
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="secondFunction()"
value="Call Function">
</form>
<p>Use different parameters inside the function and then
try...</p>
</body>
</html>
Output (Before Click):
There is a lot to learn about JavaScript functions, however we have covered the most
important concepts in this tutorial.
Nested Functions
Prior to JavaScript 1.2, function definition was allowed only in top level global code, but
JavaScript 1.2 allows function definitions to be nested within other functions as well. Still
there is a restriction that function definitions may not appear within loops or conditionals.
These restrictions on function definitions apply only to function declarations with the
function statement.
As we'll discuss later in the next chapter, function literals (another feature introduced in
JavaScript 1.2) may appear within any JavaScript expression, which means that they can
appear within if and other statements.
Example
Try the following example to learn how to implement nested functions.
<html>
<head>
<title>Funcation</title>
<script type="text/javascript">
Functions [18]
function hypotenuse(a, b) {
function square(x) { return x * x; }
return Math.sqrt(square(a) + square(b));
}
function secondFunction() {
var result;
result = hypotenuse(1, 2);
document.write(result);
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="secondFunction()"
value="Call Function">
</form>
</body>
</html>
Output (Before Click):
Function () Constructor
The function statement is not the only way to define a new function; you can define your
function dynamically using Function() constructor along with the new operator.
Note: Constructor is a terminology from Object Oriented Programming. You may not feel
comfortable for the first time, which is OK.
Syntax
Following is the syntax to create a function using Function() constructor along with the new
operator.
<script type="text/javascript">
var variablename = new Function(Arg1, Arg2...,
"FunctionBody");
</script>
Functions [19]
The Function() constructor expects any number of string arguments. The last argument is the
body of the function – it can contain arbitrary JavaScript statements, separated from each
other by semicolons.
Notice that the Function() constructor is not passed any argument that specifies a name for
the function it creates. The unnamed functions created with the Function() constructor are
called anonymous functions.
Example
Try the following example.
<html>
<head>
<title>Function () Constructor</title>
<script type="text/javascript">
var func = new Function("x", "y", "return x*y;");
function secondFunction() {
var result;
result = func(10, 20);
document.write(result);
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="secondFunction()"
value="Call Function">
</form>
</body>
</html>
Output (Before Click)
Function Literals
JavaScript 1.2 introduces the concept of function literals which is another new way of
defining functions. A function literal is an expression that defines an unnamed function.
Functions [20]
Syntax
The syntax for a function literal is much like a function statement, except that it is used as an
expression rather than a statement and no function name is required.
<script type="text/javascript">
var variablename = function(Argument List){
Function Body
};
</script>
Syntactically, you can specify a function name while creating
a literal function as follows.
<script type="text/javascript">
var variablename = function FunctionName(Argument List){
Function Body
};
</script>
But this name does not have any significance, so it is not worthwhile.
Example
Try the following example. It shows the usage of function literals.
<html>
<head>
<title>Function Literals</title>
<script type="text/javascript">
var func = function (x, y) { return x * y };
function secondFunction() {
var result;
result = func(10, 20);
document.write(result);
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="secondFunction()"
value="Call Function">
</form>
</body>
</html>
Output (Before Click)
Functions [21]
7. OPERATORS
What is an Operator?
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ‘+’
is called the operator. JavaScript supports the following types of operators.
• Arithmetic Operators
• Comparison Operators
• Logical (or Relational) Operators
• Assignment Operators
• Conditional (or ternary) Operators
Let’s have a look at all the operators one by one.
Arithmetic Operators
JavaScript supports the following arithmetic operators: Assume variable A holds 10 and
variable B holds 20, then:
Operator Description Example
+ (Addition) Adds two operands Ex: A + B will give 30
- (Subtraction) Subtracts the second Ex: A - B will give -10
operand from the first
* (Multiplication) Multiply both operands Ex: A * B will give 200
/ (Division) Divide the numerator by Ex: B / A will give 2
the denominator
% (Modulus) Outputs the remainder Ex: B % A will give 0
of an integer division
++ (Increment) Increases an integer Ex: A++ will give 11
value by one
-- (Decrement) Decreases an integer Ex: A-- will give 9
value by one
Note: Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give
"a10".
Example
The following code shows how to use arithmetic operators in JavaScript.
<html>
<head>
<title>Arithmetic Operators
</title>
</head>
<body>
<script type="text/javascript">
var a = 33;
var b = 10;
var c = "Test";
var linebreak = "<br />";
document.write("a + b = "); result = a + b;
document.write(result);
OPERATORS [23]
document.write(linebreak);
document.write("a - b = "); result = a - b;
document.write(result); document.write(linebreak);
document.write("a / b = "); result = a / b;
document.write(result); document.write(linebreak);
document.write("a % b = "); result = a % b;
document.write(result); document.write(linebreak);
document.write("a + b + c = "); result = a + b + c;
document.write(result); document.write(linebreak);
a = a++; document.write("a++ = "); result = a++;
document.write(result); document.write(linebreak);
b = b--;
document.write("b-- = "); result = b--;
document.write(result);
document.write(linebreak);
</script>
</body>
</html>
Output:
Comparison Operators
JavaScript supports the following comparison operators: Assume variable A holds 10 and
variable B holds 20, then:
Operator Description Example
== (Equal) Checks if the value of Ex: (A == B) is not true.
two operands are equal
or not, if yes, then the
condition becomes true.
!= (Not Equal) Checks if the value of Ex: (A != B) is true.
two operands are equal
or not, if the values are
not equal, then the
condition becomes true.
> (Greater than) Checks if the value of Ex: (A > B) is not true.
the left operand is
greater than the value
ofthe right operand, if
yes, then the condition
becomes true.
OPERATORS [24]
Output:
Logical Operators
JavaScript supports the following logical operators:
Assume variable A holds 10 and variable B holds 20, then:
Operator Description Example
&& (Logical AND) If both the operands are non- Ex: (A && B) is true.
zero, then the condition
becomes true.
|| (Logical OR) If any of the two operands are Ex: (A || B) is true.
non-zero, then the condition
becomes true.
! (Logical NOT) Reverses the logical state of its Ex: ! (A && B) is false.
operand. If a condition is true,
then the Logical NOT operator
will make it false.
Example
<html>
<head>
<title>Logical Operators</title>
</head>
<body>
<script type="text/javascript">
var a = true;
var b = false;
var linebreak = "<br />";
document.write("(a && b) => "); result = (a && b);
document.write(result); document.write(linebreak);
document.write("(a || b) => "); result = (a || b);
document.write(result); document.write(linebreak);
document.write("!(a && b) => "); result = (!(a && b));
document.write(result); document.write(linebreak);
</script>
</body>
</html>
Try the following code to learn how to implement Logical Operators in JavaScript.
OPERATORS [26]
Output:
Bitwise Operators
JavaScript supports the following bitwise operators: Assume variable A holds 2 and variable
B holds 3, then:
Operator Description Example
& (Bitwise AND) It performs a Boolean AND Ex: (A & B) is 2.
operation on each bit of its
integer arguments.
| (BitWise OR) It performs a Boolean OR Ex: (A | B) is 3.
operation on each bit of its
integer arguments.
^ (Bitwise XOR) It performs a Boolean exclusive Ex: (A ^ B) is 1.
OR operation on each bit of its
integer arguments. Exclusive OR
means that either operand one is
true or operand two is true, but
not both.
~ (Bitwise Not) It is a unary operator and Ex: (~B) is -4.
operates by reversing all the bits
in the operand.
<< (Left Shift) It moves all the bits in its first Ex: (A << 1) is 4.
operand to the left by the
number of places specified in the
second operand. New bits are
filled with zeros. Shifting a value
left by one position is equivalent
to multiplying it by 2, shifting
two positions is equivalent to
multiplying by 4, and so on.
>> (Right Shift) Binary Right Shift Operator. The Ex: (A >> 1) is 1.
left operand’s value is moved
right by the number of bits
specified by the right operand.
>>> (Right shift This operator is just like the >> Ex: (A >>> 1) is 1.
with Zero) operator, except that the bits
shifted in on the left are always
zero.
Example
Try the following code to implement Bitwise operator in JavaScript.
<html>
<head>
OPERATORS [27]
<title>Bitwise Operators
</title>
</head>
<body>
<script type="text/javascript">
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
var linebreak = "<br />";
document.write("(a & b) => "); result = (a & b);
document.write(result);
document.write(linebreak);
document.write("(a | b) => "); result = (a | b);
document.write(result); document.write(linebreak);
document.write("(a ^ b) => "); result = (a ^ b);
document.write(result); document.write(linebreak);
document.write("(~b) => "); result = (~b);
document.write(result); document.write(linebreak);
document.write("(a << b) => "); result = (a << b);
document.write(result); document.write(linebreak);
document.write("(a >> b) => "); result = (a >> b);
document.write(result); document.write(linebreak);
</script>
</body>
</html>
Output
Assignment Operators
JavaScript supports the following assignment operators:
Operator Description Example
= (Simple Assigns values from the right side operand Ex: C = A + B will
Assignment) to the left side operand assign the value of
A + B into C
+= (Add and It adds the right operand to the left Ex: C += A is
Assignment) operand and assigns the result to the left equivalent to C =
operand. C+A
-= (Subtract It subtracts the right operand from the left Ex: C -= A is
and operand and assigns the result to the left equivalent to C =
Assignment) operand. C-A
OPERATORS [28]
Output
Miscellaneous Operators
We will discuss two operators here that are quite useful in JavaScript: the conditional
operator (? :) and the typeof operator.
Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or false value and then
executes one of the two given statements depending upon the result of the evaluation.
Operator Description
? : (Conditional ) If Condition is true? Then value X : Otherwise value Y
Example
Try the following code to understand how the Conditional Operator works in JavaScript.
<html>
<head>
<title>Conditional Operator (? :)
</title>
</head>
<body>
<script type="text/javascript">
var a = 10;
var b = 20;
var linebreak = "<br />";
document.write("((a > b) ? 100 : 200) => "); result = (a > b)
? 100 : 200; document.write(result); document.write(linebreak);
document.write("((a < b) ? 100 : 200) => ");
result = (a < b) ? 100 : 200; document.write(result);
document.write(linebreak);
</script>
</body>
</html>
Output
OPERATORS [30]
typeof Operator
The typeof operator is a unary operator that is placed before its single operand, which can be
of any type. Its value is a string indicating the data type of the operand.
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number,
string, or boolean value and returns true or false based on the evaluation.
Here is a list of the return values for the typeof Operator.
Type String Returned by typeof
Number "number"
String "string"
Boolean "boolean"
Object "object"
Function "function"
Undefined "undefined"
Null "object"
Example
The following code shows how to implement typeof operator.
<html>
<head>
<title>typeof operator
</title>
</head>
<body>
<script type="text/javascript">
var a = 10;
var b = "String";
var linebreak = "<br />";
result = (typeof b == "string" ? "B is String" : "B is
Numeric");
document.write("Result => "); document.write(result);
document.write(linebreak);
result = (typeof a == "string" ? "A is String" : "A is
Numeric");
document.write("Result => "); document.write(result);
document.write(linebreak);
</script>
</body>
</html>
Output
SWITCH-CASE [31]
8. SWITCH-CASE
You can use multiple if...else…if statements, as in the previous chapter, to perform a
multiway branch. However, this is not always the best solution, especially when all of the
branches depend on the value of a single variable.
You can use a switch statement which handles exactly this situation, and it does so more
efficiently than repeated if...else if statements.
Flow Chart
The following flow chart explains a switch-case statement works.
Syntax
The objective of a 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)
SWITCH-CASE [32]
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
The break statements indicate the end of a particular case. If they were omitted, the
interpreter would continue executing each statement in each of the following cases.
We will explain break statement in Loop Control chapter.
Example
Try the following example to implement switch-case statement.
<html>
<head>
<title>Switch
</title>
</head>
<body>
<script type="text/javascript">
var grade = 'A';
document.write("Entering switch block<br />");
switch (grade) {
case 'A': document.write("Good job<br />");
break;
case 'B': document.write("Pretty good<br />");
break;
case 'C': document.write("Passed<br />");
break;
case 'D': document.write("Not so good<br />");
break;
case 'F': document.write("Failed<br />");
break;
default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
</script>
</body>
</html>
SWITCH-CASE [33]
Output
Break statements play a major role in switch-case statements. Try the following code that
uses switch-case statement without any break statement.
<html>
<head>
<title>Switch
</title>
</head>
<body>
<script type="text/javascript">
var grade = 'A';
document.write("Entering switch block<br />");
45
switch (grade) {
case 'A': document.write("Good job<br />"); case 'B':
document.write("Pretty good<br />"); case 'C':
document.write("Passed<br />");
case 'D': document.write("Not so good<br />"); case 'F':
document.write("Failed<br />"); default: document.write("Unknown
grade<br />")
}
document.write("Exiting switch block");
</script>
</body>
</html>
Output
FOR LOOP [34]
9. FOR LOOP
The for Loop
The ‘for’ loop is the most compact form of looping. It includes the following three important
parts:
• The loop initialization where we initialize our counter to a starting value. The
initialization statement is executed before the loop begins.
• The test statement which will test if a given condition is true or not. If the condition is
true, then the code given inside the loop will be executed, otherwise the control will
come out of the loop.
• The iteration statement where you can increase or decrease your counter.
You can put all the three parts in a single line separated by semicolons.
Flow Chart
The flow chart for loop in JavaScript would be as follows:
Syntax
The syntax of for loop is JavaScript is as follows:
for (initialization; test condition; iteration statement)
{
Statement(s) to be executed if test condition is true
}
Example
Try the following example to learn how a for loop works in JavaScript.
<html>
<head>
<title>For Loop
</title>
FOR LOOP [35]
</head>
<body>
<script type="text/javascript">
var count;
document.write("Starting Loop" + "<br />");
for (count = 0; count < 10; count++) {
document.write("Current Count : " + count);
document.write("<br />");
}
document.write("Loop stopped!");
</script>
</body>
</html>
Output
FOR-IN LOOP [36]
Syntax
The syntax of ‘for..in’ loop is:
for (variablename in object){
statement or block to execute
}
In each iteration, one property from object is assigned to variablename and this loop
continues till all the properties of the object are exhausted.
Example
Try the following example to implement ‘for-in’ loop. It prints the web browser’s
Navigator object.
<html>
<head>
<title>For IN Loop
</title>
</head>
<body>
<script type="text/javascript">
var aProperty;
document.write("Navigator Object Properties<br /> ");
for (aProperty in navigator) {
document.write(aProperty);
document.write("<br />");
}
document.write("Exiting from the loop!");
</script>
</body>
</html>
FOR-IN LOOP [37]
Output:
LOOP CONTROL [38]
Flow Chart
Example
The following example illustrates the use of a break statement with a while loop. Notice how
the loop breaks out early once x reaches 5 and reaches to document.write (..) statement just
below to the closing curly brace:
<html>
<head>
<title>Break
</title>
</head>
<body>
<script type="text/javascript">
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 20) {
if (x == 5) {
break; // breaks out of loop completely
LOOP CONTROL [39]
}
x = x + 1;
document.write(x + "<br />");
}
document.write("Exiting the loop!<br /> ");
</script>
</body>
</html>
Output
We have already seen the usage of break statement inside a switch statement.
</html>
Output
Example 2
The following example shows how to implement Label with continue.
<html>
<head>
<title>Using Labels to Control the Flow
</title>
</head>
<body>
<script type="text/javascript">
document.write("Entering the loop!<br /> ");
outerloop: // This is the label name
for (var i = 0; i < 3; i++) {
document.write("Outerloop: " + i + "<br />");
for (var j = 0; j < 5; j++) {
if (j == 3) {
continue outerloop;
}
document.write("Innerloop: " + j + "<br />");
}
}
LOOP CONTROL [42]
Syntax
The syntax of while loop in JavaScript is as follows:
while (expression){
Statement(s) to be executed if expression is true
}
Example
Try the following example to implement while loop.
WHILE LOOP [44]
<html>
<head>
<title>while Loop
</title>
</head>
<body>
<script type="text/javascript">
var count = 0; document.write("Starting Loop "); while (count
< 10) {
document.write("Current Count : " + count + "<br />");
count++;
}
document.write("Loop stopped!");
</script>
</body>
</html>
Output
Syntax
The syntax for do-while loop in JavaScript is as follows:
do{
Statement(s) to be executed;
} while (expression);
Note: Don’t miss the semicolon used at the end of the do...while loop.
Example
Try the following example to learn how to implement a do-while loop in JavaScript.
<html>
<head>
<title>while Loop
</title>
</head>
<body>
<script type="text/javascript">
var count = 0;
document.write("Starting Loop" + "<br />");
do {
document.write("Current Count : " + count + "<br />");
count++;
} while (count < 5);
document.write("Loop stopped!");
</script>
WHILE LOOP [46]
</body>
</html>
Output
ERRORS AND EXCEPTIONS [47]
Syntax Errors
Syntax errors, also called parsing errors, occur at compile time in traditional programming
languages and at interpret time in JavaScript.
For example, the following line causes a syntax error because it is missing a closing
parenthesis.
<script type="text/javascript">
window.print(;
</script>
When a syntax error occurs in JavaScript, only the code contained within the same thread as
the syntax error is affected and the rest of the code in other threads gets executed assuming
nothing in them depends on the code containing the error.
Runtime Errors
Runtime errors, also called exceptions, occur during execution (after
compilation/interpretation).
For example, the following line causes a runtime error because here the syntax is correct, but
at runtime, it is trying to call a method that does not exist.
<script type="text/javascript">
window.printme();
</script>
Exceptions also affect the thread in which they occur, allowing other JavaScript threads to
continue normal execution.
Logical Errors
Logic errors can be the most difficult type of errors to track down. These errors are not the
result of a syntax or runtime error. Instead, they occur when you make a mistake in the logic
that drives your script and you do not get the result you expected.
You cannot catch those errors, because it depends on your business requirement what type of
logic you want to put in your program.
Example
The following example demonstrates how to use a throw statement.
<!DOCTYPE html>
<html>
<head>
<title>Finally Block
</title>
<script type="text/javascript">
function myFunc() {
var a = 100;
var b = 0;
try {
if (b == 0) {
throw ("Divide by zero error.");
} else {
var c = a / b;
}
} catch (e) {
document.write("Error: " + e);
}
}
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();"
/>
</form>
</body>
</html>
Output (Before Click)
You can raise an exception in one function using a string, integer, Boolean, or an object and
then you can capture that exception either in the same function as we did above, or in another
function using a try...catch block.
Finally Statement
You can use a finally block which will always execute unconditionally after the try/catch.
Here is an example.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Finally Block
</title>
</head>
<body>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test
Input</button>
<p id="message"></p>
<script>
function myFunction() {
var message, x;
message = document.getElementById("message");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
if (x == "") throw "is empty";
if (isNaN(x)) throw "is not a number";
x = Number(x);
if (x > 10) throw "is too high";
if (x < 5) throw "is too low";
}
catch (err) {
message.innerHTML = "Input " + err;
}
finally {
document.getElementById("demo").value = "";
}
}
</script>
</body>
</html>
ERRORS AND EXCEPTIONS [51]
The onerror event handler provides three pieces of information to identify the exact nature of
the error:
• Error message: The same message that the browser would display for the given error
• URL: The file in which the error occurred
• Line number: The line number in the given URL that caused the error
Here is the example to show how to extract this information.
Example
<!DOCTYPE html>
<html>
<head>
<title>The onerror( ) Method
</title>
<script type="text/javascript">
window.onerror = function (msg, url, line) {
document.write("Message : " + msg); document.write("url :
" + url);
document.write("Line number : " + line);
}
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();"
/>
</form>
ERRORS AND EXCEPTIONS [53]
</body>
</html>
Output (Before Click)
You can display extracted information in whatever way you think it is better.
PAGE REDIRECT [54]
Example 2
PAGE REDIRECT [56]
You can show an appropriate message to your site visitors before redirecting them to a new
page. This would need a bit time delay to load a new page. The following example shows
how to implement the same. Here setTimeout() is a built-in JavaScript function which can be
used to execute another function after a given time interval.
<html>
<head>
<title>How Page Re-direction Works?</title>
<script type="text/javascript">
function Redirect() {
window.location = "http://www.kics.edu.pk";
}
document.write("You will be redirected to our main page in 10
seconds!");
setTimeout('Redirect()', 10000);
</script>
</head>
<body>
</body>
</html>
Output (Before Redirect)
Local Installation
• Go to the https://jquery.com/download/ to download the latest version available.
• Now, insert downloaded jquery-2.1.3.min.js file in a directory of your website, e.g.
/jquery.
Example
<html>
<head>
<title>The jQuery Example</title>
<script type="text/javascript" src="/jquery/jquery-
2.1.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
document.write("Hello, World!");
});
jQuery and Its Plugins [62]
</script>
</head>
<body>
<h1>Hello</h1>
</body>
</html>
Now, you can include jquery library in your HTML file as follows:
<script type="text/javascript">
$(document).ready(function () {
document.write("Hello, World!");
});
</script>
</head>
<body>
<h1>Hello</h1>
</body>
</html>
Output:
jQuery and Its Plugins [63]
#panel {
padding: 50px;
display: none;
}
</style>
</head>
<body>
<div id="flip">Click to slide down panel</div>
<div id="panel">Hello world!</div>
</body>
</html>
jQuery and Its Plugins [65]
<style>
jQuery and Its Plugins [66]
#panel, #flip {
padding: 5px;
text-align: center;
background-color: #e5eecc;
border: solid 1px #c3c3c3;
}
#panel {
padding: 50px;
display: none;
}
</style>
</head>
<body>
</body>
</html>
Output (Before Click):