Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

CSS Unit01 Final

Download as pdf or txt
Download as pdf or txt
You are on page 1of 35

Basics of JavaScript Programming

Script
 A script is a small piece of program that can add interactivity to the website. For example, a
script could generate a pop-up alert box message, or provide a dropdown menu. This script could
be JavaScript or VBScript.
 A script language is a simple programming language with which you can write scripts. A
scripting language is a form of programming language that is usually interpreted rather than
compiled.
 Conventional programs are converted permanently into executable files before they are run.
In contrast, programs in scripting language are interpreted one command at a time. Scripting
languages are often written to facilitate enhanced features of Web sites.
 JavaScript, Perl, PHP, Python, VBScript are the most popular examples of scripting Languages.

What is Client side Script?


A client-side script is a small program (or set of instructions) that is embedded (or inserted)
into a web page. It is processed within the client browser instead of the web server.
The client side script downloads at the client end from the server along with the HTML web
page it is embedded in. The web browser interprets and executes the code and then displays
the results on the monitor.
The script that executes on the user’s computer system is called client. It is embedded (or
inserted) within the HTML document or can be stored in an external separate file (known as
external script).
The script files are sent to the client machine from the web server (or severs) when they are
requested. The client’s web browser executes the script, then displays the web page, including
any visible output from the script.

Client side scripts may also have some instructions for the web browser to follow in response to
certain user actions, such as pressing a page button. They can often be looked if client want to
view the source code of web page.

Client Side Scripting (Unit 1)


Basics of JavaScript Programming

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 can be used to trap user-initiated events such as button clicks, link navigation, and
other actions that the user initiates explicitly or implicitly.

Features of JavaScript
 JavaScript is a lightweight, interpreted programming language.
 Interpreter Based Scripting Language
 Case Sensitive
 Designed for creating network-centric applications.
 Integrated with HTML.
 Open and cross-platform
 Validating User’s Input : JavaScript is very useful while using forms. It has the capability to
validate user input for errors and also saves time. If the user leaves a required field empty or
the information is incorrect, JavaScript checks for them before sending the data over to the
server.

Advantages of JavaScript
 Speed: Client-side JavaScript is very fast because it can be run immediately within the
client-side browser.
 Simplicity: JavaScript is relatively simple to learn and implement.
 Popularity: JavaScript is used everywhere on the web.
 Interoperability: JavaScript plays nicely with other languages and can be used in a huge
variety of applications.
 Server Load: Being client-side reduces the demand on the website server.
 Gives the ability to create rich interfaces.
 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
 Increased interactivity − You can create interfaces that react when the user hovers
over them with a mouse or activates them via the keyboard.

Client Side Scripting (Unit 1)


Basics of JavaScript Programming

Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It lacks the following
important features –
 Client-Side Security: Because the code executes on the users’ computer, in some cases it can
be exploited for malicious purposes. This is one reason some people choose to disable
Javascript.
 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 multi-threading or multiprocessor capabilities.

Where to write Javascript code:


1. Directly in Browser Console
2. In HTML file
3. In separate Javascript File and linking this file in HTML file
Tools to run JavaScript Code:
JavaScript Editors: Notepad,Notepad++, VS, Sublime, Eclipse, Atom
Browser: Chrome,Firefox,Safari,Edge

JavaScript Programming
Q] Explain <script> tag with example?
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 your 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.
<script ...>
JavaScript code
</script>
The script tag takes two important attributes −
1. Language − This attribute specifies what scripting language you are using. Typically, its
value will be javascript. Although recent versions of HTML (and XHTML, its successor)
have phased out the use of this attribute.

2. Type – This attribute tells the browser that script is in plain text and text is organised in
the format of javascript.
So your JavaScript segment will look like −
<script language = "javascript" type = "text/javascript">
JavaScript code
</script>

Client Side Scripting (Unit 1)


Basics of JavaScript Programming

Whitespace and Line Breaks


JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs. You can use
spaces, tabs, and newlines freely in your program and you are free to format and indent your
programs.
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 each of your statements are placed on
a separate line.
For example, the following code could be written without semicolons.
<script language = "javascript" type = "text/javascript">
document.write("Hello")
document.write("Welcome to SPC Academy")
</script>

But when formatted in a single line as follows, you must use semicolons −
<script language = "javascript" type = "text/javascript">
document.write("Hello"); document.write("Welcome to SPC Academy")
</script>

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

Case Sensitivity
JavaScript is a case-sensitive language. This means that the language keywords, variables,
function names, and any other identifiers must always be typed with a consistent capitalization
of letters.
So the identifiers Time and TIME will convey different meanings in JavaScript.

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.
Example
The following example shows how to use comments in JavaScript.
<script language = "javascript" type = "text/javascript">
// This is a comment. It is similar to comments in C++
/*
This is a multi-line comment in JavaScript
It is very similar to comments in C Programming
*/
</script>

Client Side Scripting (Unit 1)


Basics of JavaScript Programming

JavaScript Enabling
All the modern browsers such as Internet Explorer, Firefox, chrome, and Opera come with built-
in support for JavaScript. Frequently, you may need to enable or disable this support manually.

JavaScript in Internet Explorer


Here are simple steps to turn on or turn off JavaScript in your Internet Explorer −
 Follow Tools → Internet Options from the menu.
 Select Security tab from the dialog box.
 Click the Custom Level button.
 Scroll down till you find Scripting option.
 Select Enable radio button under Active scripting.
 Finally click OK and come out

JavaScript Placement
There is a flexibility given to include JavaScript code anywhere in an HTML document. However
the most preferred ways to include JavaScript in an HTML file are as follows −
 Script in <head>...</head> section.
 Script in <body>...</body> section.
 Script in <body>...</body> and <head>...</head> sections.
 Script in an external file and then include in <head>...</head> section.
In the following section, we will see how we can place JavaScript in an HTML file in different
ways.

a) JavaScript in <head>...</head> section


If you want to have a script run on some event, such as when a user clicks somewhere, then you
will place that script in the head as follows −
<html>
<head>
<script type = "text/javascript">
function sayHello()
{
alert("WELCOME TO spc World")
}
</script>
</head>
<body>
<input type = "button" onclick = "sayHello()" value = "Say Hello"/>
</body>
</html>

Client Side Scripting (Unit 1)


Basics of JavaScript Programming

b) JavaScript in <body>...</body> section


If you need a script to run as the page loads so that the script generates content in the page, then
the script goes in the <body> portion of the document. In this case, you would not have any
function defined using JavaScript. Take a look at the following code.
<html>
<head>
</head>

<body>

<script type = "text/javascript">

document.write("Hello World")

</script>

</body>
</html>

c) JavaScript in <body> and <head> Sections


You can put your JavaScript code in <head> and <body> section altogether as follows −
<html>
<head>
<script type = "text/javascript">

function sayHello()
{
alert("Welcome to spc World")
}
</script>
</head>

<body>

<script type = "text/javascript">

document.write("Hello World")

</script>

<input type = "button" onclick = "sayHello()" value = "Say


Hello" />
</body>
</html>

d) JavaScript in External File

Client Side Scripting (Unit 1)


Basics of JavaScript Programming

As you begin to work more extensively with JavaScript, you will be likely to find that there are
cases where you are reusing identical JavaScript code on multiple pages of a site.
You are not restricted to be maintaining identical code in multiple HTML files. The script tag
provides a mechanism to allow you to store JavaScript in an external file and then include it into
your HTML files.
Here is an example to show how you can include an external JavaScript file in your HTML code
using script tag and its src attribute.
<html>
<head>
<script type = "text/javascript" src =
"C:\Users\Akshay\Desktop\akshay.js">
</script>
</head>

<body>
<input type = "button" onclick = "sayHello()" value = "Say
Hello" />
</body>
</html>

To use JavaScript from an external file source, you need to write all your JavaScript source code
in a simple text file with the extension ".js" and then include that file as shown above. For
example, you can keep the following content in filename.js file and then you can
use sayHello function in your HTML file after including the filename.js file.
function sayHello()
{
alert("Welcome to Arrow")
}
document.write("I am creating javascript external code<br>");

Client Side Scripting (Unit 1)


Basics of JavaScript Programming

JavaScript Variables
JavaScript includes Variables which are defined as named memory locations. Variable stores a
single data value that can be changed later.

Variable Declaration:
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>

A variable declared without a value will have the value undefined.

Variable Initialization:
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.

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

Client Side Scripting (Unit 1)


Basics of JavaScript Programming

JavaScript Variable Scope


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

Global Variables − A global variable has global scope which means it can be defined anywhere
in your JavaScript code.

Local Variables − A local variable will be visible only within a function where it is defined.
Within the body of a function, a local variable takes precedence over a global variable with the
same name.
If you declare a local variable or function parameter with the same name as a global variable,
you effectively hide the global variable.
Example:
<script type = "text/javascript">

var a = 25; // Declare a global variable


function fun( )
{
var a = 10; // Declare a local variable
document.write("Value of a is",a);
}
fun();
</script>
This produces the following result −
Value of a is 10

Rules for JavaScript Variable Names:

1. You should not use any of the JavaScript reserved keywords as a variable name. For example,
break or boolean variable names are not valid.

2. JavaScript variable names should not start with a numeral (0-9).


They must begin with a letter or an underscore character.
For example, 123test is an invalid variable name but _123test is a valid one.

3. JavaScript variable names are case-sensitive. For example, Name and name are two different
variables.

Client Side Scripting (Unit 1)


Basics of JavaScript Programming

JavaScript Data Types

JavaScript provides different data types to hold different types of values. There are two types of
data types in JavaScript.
1. Primitive data type
2. Non-primitive (reference) data type

1. JavaScript primitive data types


JavaScript primitive data types are data types that refer to a single value.

There are five types of primitive data types in JavaScript. They are as follows:

Data Type Description Example

String represents sequence of characters e.g. "hello" var str = “Hello”;

Number represents numeric values e.g. 100 var n = 100;

Boolean represents boolean value either false or true var x =true;

Undefined represents undefined value var x = undefined

Null represents null i.e. no value at all var x = null

2. JavaScript non-primitive data types


The data types that are derived from primitive data types of the JavaScript language are known
as non-primitive data types.
It is also known as derived data types.
It contains single or multiple key-value pair/s.

The non-primitive data types are as follows:


- Object
- Array
- RegExp

Client Side Scripting (Unit 1)


Basics of JavaScript Programming

1.3 Objects
Real Life Objects, Properties, and Methods
In real life, a car is an object.
A car has properties like weight and color, and methods like start and stop:

Object Properties Methods

car.name = Fiat car.start()

car.model = 500 car.drive()

car.weight = 850kg car.brake()

car.color = white car.stop()

All cars have the same properties, but the property values differ from car to car. All cars have
the same methods, but the methods are performed at different times.

A] JavaScript Objects

 JavaScript is an object-based language. Everything is an object in JavaScript.


 All primitive data types can contain only a single thing (either a string or a number). In
contrast, objects are used to store collections of data and more complex entities.
 JavaScript objects are collections of properties and methods.

 A property is a value or set of values that is a member of an object


 A method is a function that is a member of an object.

 Objects in JavaScript may be defined as, an unordered collection of related data of


primitive or reference types in the form of "key: value" pairs,
 You access an object's properties and methods by using the dot syntax along with the
object name and its property or method.

B] Object Name
 Each object is uniquely identified by a name or ID.
 A web page contains many objects, some of which are the same kind of object. These objects
can be easily distinguishable by using its name or ID.

C] Property
 A property is a data or value associated with an object.
 Objects can have many data's associated with them depending on application of use.
 For example, a form object can have a title, a width and a height as properties whereas a
window object can have a background color, a width and height as properties.

Client Side Scripting (Unit 1)


Basics of JavaScript Programming

 Hence, each object has its own set of properties. An object can be created with curly 
brackets {...} with list of properties.
 A property is a "key: value pair, where key is a string (also called a "property name"), and
value can be anything.

D] Creating a JavaScript Object

With JavaScript, you can define and create your own objects. There are different ways to create
new objects:

 Define and create a single object, using an object literal.


 Define and create a single object, with the keyword new.
 Define an object constructor, and then create objects of the constructed type.
1. Using an Object Literal

This is the easiest way to create a JavaScript Object. Using an object literal, you both define and
create an object in one statement. An object literal is a list of name:value pairs inside curly
braces {}.

The following example creates a new JavaScript object with four properties:
syntax :
object={property1:value1,property2:value2...... propertyN:valueN}
As you can see, property and value is separated by : (colon).
Example:
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>

Spaces and line breaks are not important. An object definition can span multiple lines:
<script>
emp= {
id:102,
name:"Shyam Kumar",
salary:40000
}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>

2. Using the JavaScript Keyword new

Syntax:

var objectname=new Object();

Here, new keyword is used to create object.

Client Side Scripting (Unit 1)


Basics of JavaScript Programming

Example:
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>

3. By using an Object constructor


Here, you need to create function with arguments. Each argument value can be assigned in the
current object by using this keyword.
The this keyword refers to the current object.
Example:
<script>
function emp(id,name,salary)
{
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
</script>

E] Dot Syntax:
 The properties & methods associated with any object can be accessed by using the object
name with dot syntax.
 E.g. user.fname, user.lname & user.fullName( ).

In the following code user object is created with two properties:


1 The first property has the name fname and the value "Computer"
2. The second one has the name lname and the value "Engineering".

You can access the object properties in following two ways:


1. user.fname;
2. user[“fname”]

Example:
<html>
<head>
<title>Object</title>
</head>
<body>
<script>
var user = {

Client Side Scripting (Unit 1)


Basics of JavaScript Programming

fname: " Computer ",


lname: " Engineering”
};
document.write(“User =” + user.fname +” “+ user. lname);
</script>
</body>
</html>
Output:
User – Computer Engineering

F] Method
A method is a set of statements (actions) performed by an object when it receives a message.
On a form when you click on Submit button, the form is submitted to server side application.
Here Submit is an object, and clicking on it causes the button to process a method.

Example:

<script>
var person = {
firstName: "John",
lastName : "Doe",
fullName : function()
{
return this.firstName + " " + this.lastName;
}

};
document.write(“User Name is:” + person.fullname());
</script>

The this Keyword


In a function definition, this refers to the "owner" of the function.
In the example above, this is the person object that "owns" the fullName function.
In other words, this.firstName means the firstName property of this object.

Client Side Scripting (Unit 1)


Basics of JavaScript Programming

1.5 JavaScript Operator


JavaScript operators are symbols that are used to perform operations on operands.
JavaScript supports the following types of operators.

 Arithmetic Operators
 Comparison Operators
 Logical (or Relational) Operators
 Assignment Operators
 Conditional (or ternary) Operators
Lets have a look on all operators one by one.

1) Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on the operands.
Assume variable A holds 10 and variable B holds 20, then −
Sr. Operator & Description Example

1 + (Addition): Adds two operands Ex: A + B will give 30

2 - (Subtraction): Subtracts the second operand from the first Ex: A - B will give -10

3 * (Multiplication): Multiply both operands Ex: A * B will give 200

4 / (Division): Divide the numerator by the denominator Ex: B / A will give 2

5 % (Modulus): Outputs the remainder of an integer division Ex: B % A will give 0

6 ++ (Increment): Increases an integer value by one Ex: A++ will give 11

7 -- (Decrement): Decreases an integer value by one Ex: A-- will give 9

Ex. A**B will give A


8 ** (Exponentiation)
raised to power B

Client Side Scripting (Unit 1)


Basics of JavaScript Programming

2) Assignment Operators
JavaScript supports the following assignment operators −
Sr. Operator & Description Example

= (Simple Assignment )
Ex: C = A + B will assign
1 Assigns values from the right side operand to the left side
the value of A + B into C
operand

+= (Add and Assignment)


Ex: C += A is equivalent to
2 It adds the right operand to the left operand and assigns the
C=C+A
result to the left operand.

−= (Subtract and Assignment)


Ex: C -= A is equivalent to
3 It subtracts the right operand from the left operand and
C=C-A
assigns the result to the left operand.

*= (Multiply and Assignment)


Ex: C *= A is equivalent to
4 It multiplies the right operand with the left operand and
C=C*A
assigns the result to the left operand.

/= (Divide and Assignment)


Ex: C /= A is equivalent to
5 It divides the left operand with the right operand and assigns
C=C/A
the result to the left operand.

%= (Modules and Assignment)


Ex: C %= A is equivalent
6 It takes modulus using two operands and assigns the result to
to C = C % A
the left operand.

Ex. C**=A is equivalent to


7 **=
C=C*A

Client Side Scripting (Unit 1)


Basics of JavaScript Programming

3) Comparison Operators
JavaScript supports the following comparison operators −
Assume variable A holds 10 and variable B holds 20, then −
Sr. Operator & Description Example

= = (Equal)
1 Checks if the value of two operands are equal or not, if yes, then the Ex: (A == B) is not true .
condition becomes true.

!= (Not Equal)
2 Checks if the value of two operands are equal or not, if the values Ex: (A != B) is true.
are not equal, then the condition becomes true.

> (Greater than)


3 Checks if the value of the left operand is greater than the value of Ex: (A > B) is not true.
the right operand, if yes, then the condition becomes true.

< (Less than)


4 Checks if the value of the left operand is less than the value of the Ex: (A < B) is true.
right operand, if yes, then the condition becomes true.

>= (Greater than or Equal to)


5 Checks if the value of the left operand is greater than or equal to the Ex: (A >= B) is not true .
value of the right operand, if yes, then the condition becomes true.

<= (Less than or Equal to)


6 Checks if the value of the left operand is less than or equal to the Ex: (A <= B) is true.
value of the right operand, if yes, then the condition becomes true.

Ex: A=5 and B=”5”


7 === (equal value and equal type)
Then A ===B is False

Ex: A=5 and B=”5”


8 !== (Not equal value or Not equal type)
Then A !==B is True

Client Side Scripting (Unit 1)


Basics of JavaScript Programming

4) Logical Operators
Assume variable A holds 10, variable B holds 20, variable C holds 30, then −
Sr. Operator & Description Example

&& (Logical AND)


Ex: (A<B && B < C) is
1 If both the operands are true, then the condition becomes
true.
true, otherwise it returns false.

|| (Logical OR)
2 If any of its arguments are true, it returns true, otherwise it Ex: (A>B || B < C) is false.
returns false.

! (Logical NOT)
3 If a condition is true, then the Logical NOT operator will Ex: ! (A && B) is false.
make it false and vice versa.

5) Bitwise Operators
Assume variable A holds 2 and variable B holds 3, then −
Sr. Operator & Description Example

& (Bitwise AND)


1 It performs a Boolean AND operation on each bit of its integer Ex: (A & B) is 2.
arguments.

| (BitWise OR)
2 It performs a Boolean OR operation on each bit of its integer Ex: (A | B) is 3.
arguments.

^ (Bitwise XOR)
It performs a Boolean exclusive OR operation on each bit of its integer
3 Ex: (A ^ B) is 1.
arguments. Exclusive OR means that either operand one is true or
operand two is true, but not both.

~ (Bitwise Not)
4 It is a unary operator and operates by reversing all the bits in the Ex: (~B) is -4.
operand.

<< (Left Shift)


It moves all the bits in its first operand to the left by the number of
5 places specified in the second operand. New bits are filled with zeros. Ex: (A << 1) is 4.
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)


6 Binary Right Shift Operator. The left operand’s value is moved right by Ex: (A >> 1) is 1.
the number of bits specified by the right operand.

Client Side Scripting (Unit 1)


Basics of JavaScript Programming

6) Ternary Operator
JavaScript includes special operator called ternary operator :? that assigns a value to a variable
based on some condition. This is like short form of if-else condition.
Syntax:
<condition> ? <value1> : <value2>;
Ternary operator starts with conditional expression followed by ? operator. Second part ( after
? and before : operator) will be executed if condition turns out to be true. If condition becomes
false then third part (after :) will be executed.
Example:
var a = 10, b = 5;
var c = a > b? a : b; // value of c would be 10
var d = a > b? b : a; // value of d would be 5

Conditional Statements
While writing a program, there may be a situation when you need to adopt one out of a given set
of paths. In such cases, you need to use conditional statements that allow your program to make
correct decisions and perform right actions.
JavaScript supports conditional statements which are used to perform different actions based
on different conditions.

A] if..else statement
Flow Chart of if-else

JavaScript supports the following forms of if..else statement −


 if statement
 if...else statement
 if...else if... statement.

Client Side Scripting (Unit 1)


Basics of JavaScript Programming

1) 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
}
Here a JavaScript expression is evaluated. If the resulting value is true, the given statement(s)
are executed. If the expression is false, then no statement would be executed. Most of the times,
you will use comparison operators while making decisions.

Example
Try the following example to understand how the if statement works.

<html>
<body>
<script type = "text/javascript">
var age = 20;
if( age > 18 )
{
document.write("Qualifies for driving ");
}
</script>
</body>
</html>

Output
Qualifies for driving

2) if...else statement

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

Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s) in
the ‘if’ block, are executed. If the expression is false, then the given statement(s) in the else
block are executed.

Client Side Scripting (Unit 1)


Example

Try the following code to learn how to implement an if-else statement in JavaScript.
<html>
<body>
<script type = "text/javascript">
var age = 15;

if( age > 18 )


{
document.write("<b>Qualifies for driving</b>");
}
else
{
document.write("<b>Does not qualify for driving</b>");
}
</script>
</body>
</html>

Output
Does not qualify for driving

3) if...else if... statement

The if...else if... statement is an advanced form of if…else that allows JavaScript to make a correct
decision out of several conditions.

Syntax
The syntax of an if-else-if statement is as follows −
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
}
It is just a series of if statements, where each if is a part of the else clause of the previous
statement. Statement(s) are executed based on the true condition, if none of the conditions is
true, then the else block is executed.

Client Side Scripting (Unit 1)


Example
Try the following code to learn how to implement an if-else-if statement in JavaScript.

<!DOCTYPE html>
<html>
<head>
<title>First Page</title>
<script type = "text/javascript">

var m1=30,m2=40,m3=35,m4=34,m5=30;
var total=m1+m2+m3+m4+m5;
var per=total/5
document.write("Total is "+total)
document.write("<br>")
document.write("Percentage is "+per)
document.write("<br>")

if(per>70)
{
document.write("Distinction")
}

else if(per>60)
{
document.write("First Class")
}
else if(per>50)
{
document.write("Second Class")
}
else if(per>40)
{
document.write("Pass")
}
else
{
document.write("Fail")
}

</script>
</head>
<body>
</body>
</html>

Client Side Scripting (Unit 1)


4) nested if else statement
Nested if statements mean if statement inside another if statement.
Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}

Example:
<!DOCTYPE html>
<html>
<head>
<title>Nested If Else</title>
<script type="text/javascript">
var a=10,b=40,c=30;
if(a>b)
{
if(a>c)
{
document.write("Largest number is "+a)
}
else
{
document.write("largest number is "+c)
}
}
else
{
if(b>c)
{
document.write("Largest number is "+b)
}
else
{
document.write("Largest number is "+c)
}
}
</script>
</head>
<body>
</body>
</html>

Client Side Scripting (Unit 1)


B) switch statement
The JavaScript switch statement is used in decision making.
The switch statement evaluates an expression and executes the corresponding body that
matches the expression's result.
Syntax:
switch (variable/expression)
{
case value1:
// body of case 1
break;
case value2:
// body of case 2
break;
case valueN:
// body of case N
break;
default:
// body of default
}

The switch statement evaluates a variable/expression inside parentheses ().


 If the result of the expression is equal to value1, its body is executed.
 If the result of the expression is equal to value2, its body is executed.
 This process goes on. If there is no matching case, the default body executes.

Notes:
 The break statement is optional. If the break statement is encountered, the switch statement
ends.
 If the break statement is not used, the cases after the matching case are also executed.
 The default clause is also optional.

Flowchart:

Client Side Scripting (Unit 1)


Example:
<html>
<body>
<script type = "text/javascript">
var grade = 'd';
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 'E': document.write("Failed<br />");
break;
default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
</script>
</body>
</html>
Output
Entering switch block
Good job
Exiting switch block

Client Side Scripting (Unit 1)


Example 2
<!DOCTYPE html>
<html>
<head>
<title>Switch</title>
<script type = "text/javascript">

var operator = '+';


var number1=23,number2=10,result;
document.write("Entering switch block<br />");
switch(operator)
{
case '+':
result = number1 + number2;
document.write(result)
break;
case '-':
result = number1 - number2;
document.write(result)
break;
case '*':
result = number1 * number2;
document.write(result)
break;
case '/':
result = number1 / number2;
document.write(result)
break;
case '%':
result = number1 % number2;
document.write(result)
break;

default:
document.write("Wrong Arithmetic Operator")
break;
}

</script>
</head>
<body>
</body>
</html>

Client Side Scripting (Unit 1)


Loop in JavaScript
While writing a program, you may encounter a situation where you need to perform an action
over and over again. In such situations, you would need to write loop statements to reduce the
number of lines.

1) The while Loop


The purpose of a while loop is to execute a statement or code block repeatedly as long as
an expression is true. Once the expression becomes false, the loop terminates.
Syntax:

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

 A while loop evaluates the condition inside the parenthesis ().


 If the condition evaluates to true, the code inside the while loop is executed.
 The condition is evaluated again.
 This process continues until the condition is false.
 When the condition evaluates to false, the loop stops.

Flow Chart

Client Side Scripting (Unit 1)


Example:

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

<p>Set the variable to different value and then try...</p>


</body>
</html>

Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
Set the variable to different value and then try...

Client Side Scripting (Unit 1)


2) 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.
Flow Chart

Syntax
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>
<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!");
//-->

Client Side Scripting (Unit 1)


</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Loop Stopped!
Set the variable to different value and then try...

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

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

Client Side Scripting (Unit 1)


Example

<html>
<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>
<p>Set the variable to different value and then try...</p>
</body>
</html>

Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
Set the variable to different value and then try...

Client Side Scripting (Unit 1)


break statement
The break statement is used to terminate from the loop immediately. When a break statement is
encountered inside a loop, the loop iteration stops there, and control returns from the loop
immediately to the first statement after the loop.
Example:
<script type="text/javascript">
var count;
document.write("Starting Loop" + "<br />");
for(count = 0; count < 10; count++)
{
if(count==5)
{
break
}
document.write("Current Count : " + count );
document.write("<br />");
}
</script>

Output:
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4

continue statement
The continue statement in Java is used to skip the current iteration of a loop.

<script type="text/javascript">
var count;
document.write("Starting Loop" + "<br />");

for(count = 0; count < 10; count++)


{
if(count==5)
{
continue
}
document.write("Current Count : " + count );
document.write("<br />");

}
</script>

Client Side Scripting (Unit 1)


Output:
Starting Loop
Current Count: 0
Current Count: 1
Current Count: 2
Current Count: 3
Current Count: 4
Current Count: 6
Current Count: 7
Current Count: 8
Current Count: 9

JavaScript Values or Literals:

1. Array literals
In Javascript, an array literal is a list of expressions, each of which represents an array element,
enclosed in a pair of square brackets ' [ ] ' . When an array is created using an array literal, it is
initialized with the specified values as its elements, and its length is set to the number of
arguments specified. If no value is supplied it creates an empty array with zero length.

Creating an empty array :


var fruits = [ ];
Creating an array with four elements.
var fruits = ["Orange", "Apple", "Banana", "Mango"]

2. Integers literals
An integer must have at least one digit (0-9).
No comma or blanks are allowed within an integer.
It does not contain any fractional part.
It can be either positive or negative if no sign precedes it is assumed to be positive.
In JavaScript, integers can be expressed in three different bases.

1. Decimal ( base 10)


Decimal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and there will be no
leading zeros.
Example: 123

2. Hexadecimal ( base 16)


Hexadecimal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and letters A, B, C, D,
E, F or a, b, c, d, e, f. A leading 0x or 0X indicates the number is hexadecimal.
Example: 0x123

3. Octal (base 8)
Octal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7. A leading 0 indicates the number
is octal.
Example: 0123

Client Side Scripting (Unit 1)


3. Floating number literals
A floating number has the following parts.
 A decimal integer.
 A decimal point ('.').
 A fraction.
Example:
8.2935
-14.72
4. Boolean literals
The Boolean type has two literal values: true and false

5. Object literals
An object literal is zero or more pairs of comma-separated list of property names and
associated values, enclosed by a pair of curly braces.
In JavaScript an object literal is declared as follows:

1. An object literal without properties:


var student = { }

2. An object literal with a few properties :


var student =
{
First-name : "Akshay",
Last-name : "Rayy",
Roll-No : 12
};

Syntax Rules
There is a colon (:) between property name and value.
A comma separates each property name/value from the next.
There will be no comma after the last property name/value pair.
6. String literals

A string literal is zero or more characters, either enclosed in single quotation (') marks or
double quotation (") marks.
You can also use + operator to join strings.
The following are the examples of string literals :

string1 = "computer"
string1 = 'engineering.com'
string1 = "1000"
string1 = "google" + ".com"

Client Side Scripting (Unit 1)


Main Event
Event is something that causes JavaScript to execute the code.
JavaScript's interaction with HTML is handled through events that occur when the user or the
browser manipulates a page.
When the page loads, it is called an event.
When the user clicks a button, that click to is an event.
Other examples include events like pressing any key, closing a window, resizing a window, etc.
Each available event has an event handler, which is a block of code (usually a JavaScript
function) that runs when the event fires.
Execution of appropriate code on occurrence of event is called event handling.

Client Side Scripting (Unit 1)

You might also like