You are on page 1of 35

+

WEB SCRIPTING - INTRODUCTION


JAVASCRIPT

HTML is used to create web pages.


Style sheets(CSS) provide the capability to control the way in which HTML elements are laid out and
displayed.
Web scripting is used to create dynamic web pages to make the pages more interactive and
responsive.Web scripting can be done using any one of the scripting languages.
JavaScript is the world's most popular lightweight, interpreted compiled programming language.
It is also known as scripting language for web pages.

WHAT IS SCRIPTING LANGUAGE:


Scripting Language is a lightweight programming language.Scripting Languages are not needed to be
compiled. The language is interpreted at runtime.

Scripting Language are two types


• Client -Side Scripting
• Server-Side Scripting
JavaScript can be used for both Client-Side as well as Server- Side

Client-Side JavaScript (CSJS) -- an extended version of JavaScript that enables the enhancement and
manipulation of web pages and client browsers.
Server-Side JavaScript (SSJS) -- an extended version of JavaScript that enables back-end access to
databases, file systems, and servers.

What is JavaScript?
● JavaScript was designed to add interactivity to HTML pages
● JavaScript is a case sensitive scripting language for web pages.
● A scripting language is a lightweight programming language
● JavaScript is usually embedded directly into HTML pages
● JavaScript is an interpreted language (means that scripts execute without preliminary
compilation)
● Everyone can use JavaScript without purchasing a license .

What can we build using JavaScript ?


JavaScript is a widely-used programming language. Given below are some domains/products that can be
built using JavaScript:
● Websites: It helps users to interact with the website. For eg. clicking on buttons(Respond to user
actions such as mouse clicks / key presses.), saving details, uploading details on the website, etc.
● Web Servers: We can make robust server applications using JavaScript. To be precise we use
JavaScript frameworks like Node.js and Express.js to build these servers.Java Script validates
form data before it is sent to the server
● Game Development: In Game Development industry, JavaScript is used widely. With the
addition of HTML5 Canvas, it’s now possible to make 2D and 3D games in JavaScript very
efficiently.
● 3D Drawings: JavaScript in addition with HTML Canvas is used to make three-dimensional
graphics.
● Mobile Apps: Mobile applications are the most popular modes of communicating these days.
JavaScript also used to design mobile applications. There are many JavaScript frameworks using
which we can make android, IOS, and hybrid apps.
● Smartwatch Apps: The popular smartwatch maker Pebble has created Pebble.js, a small
JavaScript framework that allows a developer to create an application for the Pebble line of
watches in JavaScript.

Are Java and JavaScript the same? NO!!!!


Java and JavaScript are two completely different languages in both concept and design!
Java (developed by Sun Microsystems) is a powerful and much more complex programming language -
in the same category as C and C++.

Writing JavaScript code


● Any text editor (e.g., Notepad, Emacs)
● Specialized software (e.g., MS Visual InterDev)

Executing JavaScript
● Load into browser (need HTML document)
● Browser detects syntax and run-time errors

JavaScript can be added to your HTML file in two ways:


● Internal JS: We can add JavaScript directly to our HTML file by writing the code inside the
<script> tag. The <script> tag can either be placed inside the <head> or the <body> tag
according to the requirement.
● External JS: We can write JavaScript code in other file having an extension .js and then link this
file inside the <head> tag of the HTML file in which we want to add this code.

Syntax:
<script>
// JavaScript Code
</script>

Why to learn JavaScript ?


JavaScript is the most popular and hence the most loved language around the globe. Apart from this,
there are abundant reasons to learn it. Below are a listing of few important points:
● No need of compilers: Since JavaScript is an interpreted language, therefore it does not
need any compiler for compilations.
● Used both Client and Server-side: Earlier JavaScript was used to build client-side
applications only, but with the evolution of its frameworks namely Node.js and Express.js,
it is now widely used for building server-side applications too.
● Helps to build a complete solution: As we saw, JavaScript is widely used in both client and
server-side applications, therefore it helps us to build an end-to-end solution to a given
problem.
● Used everywhere: JavaScript is so loved because it can be used anywhere. It can be used to
develop websites, games or mobile apps, etc.
● Huge community support: JavaScript has a huge community of users and mentors who love
this language and take it’s legacy forward.
Examples:
<html> <html>
<body> <body>
<script type="javascript"> <script type="text/javascript">
document.write("Hello World!"); document.write("<b>Hello World!</b>");
</script> </script>
</body> </body>
</html> </html>

<html> <html>
<body> <head>
<h1>My First Web Page</h1> </head>
<p>My first paragraph.</p> <body >
<script type="text/javascript"> <script type="text/javascript">
document.write(5 + 6); document.write("This is the web page");
</script> alert("This is an alert box .Click to close");
</body> </script>
</html> </body>
</html>

How to add JavaScript code

● Embedded scripts
Embed JavaScript code in an XHTML document—either in the head or in the body.

<script type=“text/javascript”>
x=3; y=9;
document.writeln( x + y );
</script>

● Inline Code
Add dynamic functionality to an individual element
<img onMouseOver=“doThisFunction(this)”>

● Inserting external scripts


Insert a file with “.js” extension that contains JavaScript code
<script type=“text/javascript” src=“external.js” />
JavaScript libraries can be shared by multiple XHTML
documents
The following example shows the three ways of including JavaScript in XHTML:

<html>
<head>
<title> Incorporating Javascript</title>
<script type="text/javascript" src="hello.js"> </script># external js
<script type="text/javascript"> # internal js
<!--
document.write("<h1>I'm generated by a script in the header</h1>");
//-->
</script>
</head>
<body> <!-- Document content -->
<h1> Incorporating Javascript</h1>
<script type="text/javascript">
<!--
document.write("<p>I'm generated by a script in the body</p>");
//-->
</script>
</body> </html>

document. write(String);

Its the basic JavaScript command used to display string on web page.
When browser encounter document.write(string) statement inside <script></script> tag it will display
the string on webpage. We can add HTML tags inside string to format the output of string

Example:
Putting a script in <head>
In the example, we have included two (very simple) scripts in the head region of the page. The first is
called in from an external file, the second is written within the page itself. These scripts are executed
when the page is loaded, which is why the text that they generate is the first thing to appear on the page.
The exception to this is if these scripts define functions, in which case the function is only executed
when it is called.

Scripts in <body>
Scripts that are placed in the <body> of the document are called as they are loaded in, and so any
content that they generate is placed at the point where the script is called.

Syntax rules of JavaScript


● Statements may or may not contain a semicolon at the end.
● Multiple statements on one line must be separated by a semicolon.eg: a=10; b=20
● JavaScript is case sensitive.Not using the proper uppercase and lowercase letters is a syntax error.
● Comments do not cause the browser to perform any action when the script is interpreted; rather,
comments are ignored by the JavaScript interpreter.
● A single-line comment begins with the characters // and terminate at the end of the line.
● Multiple-line comments begin with delimiter /* and end with delimiter */. All text between the
delimiters of the comment is ignored by the compiler.

INPUT/OUTPUT IN JAVASCRIPT

JavaScript is special from other languages because it can accept input and produce output on the basis of
that input in the same page.
Functions to show output:
1)window.alert( )
2)window.status( )
3)document.write( )
4)document.writeln( )

Functions for taking Input from User


1)window.prompt( )
2)window.confirm( )

window.alert(): This function show the message in a small messagebox . The messagebox contains the
string and an "OK"button on it. If the user presses the "OK" button the messagebox disappears. The
message to be displayed has to be
passed as parameter
window.alert()
Code example :
<html>
<body>
<script language="Javascript">
window.alert ("Hello");
window. alert(“bye”)
</script>
</body>
</html>
Output:

window.status():
This function show the message in statusbar . The message to be displayed has to be passed
as parameter window.status()
Code example :
<html>
<body>
<script language="Javascript">
window.status ("Welcome to JavaScript“)
</script >
</body>

window.prompt( ): This function is used to get any value from the user. This function takes two
optional parameters . Returns the value entered by the user in String format, however if user press
"cancel" returns "Null"
String= window.prompt("Question","default answer")

Code example :
<html>
<body>
<script language="Javascript">
var s; #optional statement
s = window.prompt("What is your name ?", "your name here" );# The value user inputs will be stored
in the variable s
document.write( s);
</script >
</body>
</html>
The above program asks user his name, and when the user enters his name and
press "OK", the name of user is printed.
window.confirm() :
This function prompts the user to confirm the decision. It shows a messageBox with two buttons "OK"
and "CANCEL" on it. If user press "OK" it returns "true" , if user press "CANCEL" it returns false.
<html>
<body>
<script language="Javascript">
var ans;
ans = window.confirm("Are you ready?")
document.write(ans)
if (ans==true) // check users response
document.writeln( "Start learning JavaScript");
else
document.writeln( "Try later");
</script >
</body>
</html>
document. write(String);
Basic JavaScript command used to display string on web page.When browser encounter inside
document.write(string) statement <script></script> tag it will display the string on webpage. We can
add HTML tags inside string to format the output of string

document.writeln(string)
Writes a line to the page with a carriage return at the end.Must be between <PRE> … </PRE> tags

<html> <body>
<script Language=“JavaScript”>
document.writeln("1");
document.writeln("2");
document.writeln("3");
document.writeln("4");
</script>
<script Language=“JavaScript”>
document.write("<pre>")
document.writeln("1");
document.writeln("2");
document.writeln("3");
document.writeln("4");
document.write("</pre>")
</script>
</body></html>

HTML Forms and JavaScript

• JavaScript is very good at processing user input in the web browser


• HTML <form> elements receive input
• Forms and form elements have unique names
– Each unique element can be identified
– Uses JavaScript Document Object Model (DOM)

Naming Form Elements in HTML

<form name="addressform">
Name: <input name="yourname"><br />
Phone: <input name="phone"><br />
Email: <input name="email"><br />
</form>

Syntax:
document.formname.elementname.value

Using Form Data

Personalising an alert box

<form name="alertform">
Enter your name:
<input type="text" name="yourname">
<input type="button" value= "Go"
onClick="window.alert('Hello ' + →
document.alertform.yourname.value);">
</form>
JAVASCRIPT PROGRAMMING

A program can do many things, including calculations, sorting names, preparing phone lists, displaying
images, validating forms, etc. But to do anything, the program works with the data that is given to it.
Data types specify what kind of data, such as numbers and characters, can be stored and manipulated
within a program. JavaScript supports a number of fundamental data types. These types can be broken
down into two categories:

• primitive data types(Number,String,Boolean,Null,Undefined )


• composite data types(Array, Object,Function)

Primitive Data Types


Primitive data types are the simplest building blocks of a program. They are types that can be assigned a
single literal value such as the number 5.7, or a string of characters such as “hello”.
JavaScript supports three core or basic data types:
• numeric
• string
• boolean

In addition to the three core data types, there are two other special types that consist of a single value:
• null
• undefined

Numeric Literals: JavaScript supports both integers and floating-point numbers. Integers are whole
numbers and do not contain a decimal point, such as 123 and –6. Integers can be expressed in decimal
(base 10), octal (base 8), and hexadecimal (base 16), and are either positive or negative values.
Floating-point numbers are fractional numbers such as 123.56 or –2.5. They must contain a decimal
point or an exponent specifier, such as 1.3e–2. The letter “e” for expo- nent notation can be either
uppercase or lowercase. JavaScriptnumbers can be very large (e.g., 10308 or 10–308 ). 12345 integer
23.45 float .234E-2 scientific notation .234e+3 scientific notation 0x456fff hexadecimal 0x456FFF
hexadecimal 0777 octal

String Literals and Quoting: String literals are set of characters enclosed in either double or single
quotes. The quotes must be matched. If the string starts with a single quote, it must end with a matching
single quote, and likewise if it starts with a double quote, it must end with a double quote. Single quotes
can hide double quotes, and double quotes can hide single quotes:
var oldcar="Big Brown Station Wagon";
var mycomputer="Pentium 3, 500 MHz, 128MB RAM";
var oldcomputer=‘386 SX, 40 mHz, 8MB RAM’;
var jibberish="what? cool! I am @ home 4 now. (cool, right?)";
An empty set of quotes is called the null string.
Eg: “ ”
If a number is enclosed in quotes, it is considered a string; for example, “5” is a string, whereas 5
is a number.

Trying to close the string with the wrong type of quotation mark, or leaving out an opening or closing
quotation mark, will cause problems.
var mycar="Red Corvette';
var myhouse= 'small brick house";
var mycomputer="Pentium 3, 500 mHz, 128MB RAM;

These mistakes will result in an “Unterminated String” error in the Web browser. Strings are called
constants or literals. The string value “hello” is called a string constant or literal. To change a string
requires replacing it with anotherstring. Strings can contain escape sequences (a single character
preceded with a backslash).

Escape sequences are a mechanism for quoting a single character

The escape sequences will work only if in a tag or an alert dialog box.
STRING CONCATENATION

The process of joining strings together is called concatenation.


● The string concatenation operator is a plus sign (+).
● Its operands are two strings.
● If one string is a number and the other is a string, JavaScript will still concatenate them as
strings.
● If both operands are numbers, the + will be the addition operator.

The following examples clarify the above points:


document.write("pop" + "corn");
output →“popcorn”

document.write("Route " + 66);


output →“Route 66”
The expression 5 + 100 results in 105, whereas “5” + 100 results in “5100”.

Boolean Literals:
Boolean literals are logical values that have only one of two values, true or false. You can think of the
values as yes or no, on or off, or 1 or 0. They are used to test whether a condition is true or false. When
using numeric comparison and equality operators, the value true evaluates to 1 and false evaluates to 0.

Null and Undefined:


The null keyword represents “no value,” meaning “nothing,” not even an empty string or zero. It is a
type of JavaScript object.It can be used to initialize a variable so that it does not produce errors or to
clear the value of a variable, so that there is no longer any data associated with that variable, and the
memory used by it is freed. When a variable is assigned null, it does not contain any valid data type. A
variable that has been declared, but given no initial value, contains the value undefined and will produce
a runtime error if you try to use it. (If you declare the variable and assign null to it, null will act as a
placeholder and you will not get an error.) The word undefined is not a keyword in JavaScript. If
compared with the == equality opera-tors, null and undefined are equal, but if compared with the
identity operator, they are not identical

Variables:
● A variable is a name given to a memory location to store value in the computer’s main storage.
● The keyword var is used to declare variable.(optional).
● It is a name used in the program that represents data (value).
● The value assigned to the variable name may change (vary) as the program is executed.
● The program can always access the current value of the variable by referring to its name.

Rules for naming a Javascript variable (identifier) :


1. Variable name should start with an alphabet (letter) / an underscore or $.
2. Variable name may contain more than one character. Second characters onwards we may use only
alphabets or digit or underscore or $.
3. No special characters are allowed in a variable name except underscore /$.
4. A variable name is case sensitive. Uppercase and lowercase letters are distinct. Sum, sum, SUM
and sUm are treated as four different variable names
5. A variable name cannot be a keyword.

Examples of correct identifiers:


var New = 2; // Here N is capital
var _2Pac; // This identifier begins with _ //
var 2_Pac // Inavalid variable name

The following is more appropriate:


var greeting = 'Hello';
var n = 100; // Undescriptive
var numberOfClients = 100; // Descriptive
// Overdescriptive identifier:
var numberOfPrivateClientOfTheFirm = 100;
Variable Declaration:
Variables must be declared before they can be used. To make sure that variables are declared first, you
can declare them in the head of the HTML document.
There are two ways to declare a variable: with or without the keyword var.
You can assign a value to the variable (or initialize a variable) when you declare it, but it is not
mandatory, unless you omit the var keyword. If a variable is declared but not initialized, it is
“undefined.”
JavaScript is a loosely typed language:
•Data Type of Variable need not be specified during declaration.
•Data types are automatically converted during script execution

Variables can be declared & Initialized using the var statement and = assignment operator

SYNTAX:
var variable_name = value; // initialized var variable_name; // uninitialized variable_name;

var some = value


var firstname=“Vinod”;
var Roll=8;
Note:Variables can also be created & initialized without using var statement but with =
assignment operator

firstname=“Vinod”
Roll=8;

Output:
How JavaScript Converts Data Types:

Variable Assignment Conversion


var item = 5.5; Assigned a float
item = 44; Converted to integer
item = "Today was bummer"; Converted to string
item = true; Converted to Boolean
item = null; Converted to the null value

TYPE CASTING

It’s also possible to convert values using a process called type casting. Type casting allows you to access
a specific value as if it were of a different type. Three type casts are available in JavaScript:
Boolean(value) – casts the given value as a Boolean Number(value) – casts the given value as a number
(either integer or floating-point) String(value) – casts the given value a string

Number("42"); // returns 42
String(42); // returns "42"
Boolean(42); // returns true

Conversion Rules

JavaScript will attempt to carry out the specified conversions in the following situations: Boolean is
converted to a Number (1/0) before comparison. In a Number comparison, if an entry is NaN it will be
converted to false. Also when comparing a Number, if an Object is entered it will attempt to cast it to an
Integer. If two Objects are compared it is the memory address that is checked for comparison. The
Literals ‘null’ and ‘Undefined’ are judged to be the same entity. They will not cast to 0, “” or false. If a
String and a Number are compared, the String will be cast to an Integer. If an Object and a String are
compared, the Object will be cast to a String.

// Type conversion is performed before comparison


var v1 = ("5" = = 5); // true
// No implicit type conversion.
// True if only if both types and values are equal

var v2 = ("5" = = 5); // false


var v3 = (5 = = 5.0); // true
var v4 = (true = = 1); // true (true is converted to 1)
var v5 = (true = = 2); // false (true is converted to 1)
var v6 = (true = = "1") // true

Conversion to Strings
All Primitive data types in JavaScript are included with a ‘toString()’ method which can be called
manually to convert the data type to a string. When dealing with floats, JavaScript will not maintain
decimal places that are not required.
This method also has an optional radix parameter which can be used to change the base level of the
returned number.

var intInteger = 99;


document.write( intInteger.toString() );
// outputs: "99"

var fltFloat = 99.99;


document.write( fltFloat.toString() );
// outputs: "99.99"

var fltFloat = 99.00;


document.write( fltFloat.toString() );
// outputs: "99"

var bolBoolean = false;


document.write( bolBoolean.toString() );
// outputs: "false";

var intInteger = 99;


document.write( intInteger.toString( 2 ) );
document.write( intInteger.toString( 8 ) );
document.write( intInteger.toString( 16 ) );
// outputs: "1100011"; - Binary
// outputs: "63"; - Hex
// outputs: "143"; - Octal

Numbers As there are two data types within the term of Number, Integers and Floats, there are two
functions for converting primitive data types into numbers. These are ‘parseInt()’ and ‘parseFloat()’.
‘parseInt()’ function can receive an option radix parameter ‘parseFloat()’function cannot. These methods
will convert up to the first invalid character and return the result. It is also worthy of note that any
number passed to the ‘parseInt()’ function with a leading ’0′ will be treated as an octal number, rather
than a decimal.

var strString= "40 string";


document.write( parseInt(strString) );
// outputs: 40

var strString= "string 40";


document.write( parseInt(strString) );
//outputs:"NaN" -The string must start with number

var strString= "40";


document.write( parseInt(strString) );
// outputs: 40 - Treated as a decimal by default

var strString= "040";


document.write( parseInt(strString) );
document.write( parseFloat(strString) );
document.write( Number(strString) );
// outputs: 32 -Converted to an octal due to leading '0'
// outputs:40 -Will only parse to decimal no.
// outputs: 40 - Cast not parsed, so is not converted

Number accepts parameters, that are string representations of decimal, octal or hexadecimal numbers.
Number("12"); // decimal, 12
Number("0x12"); // hexadecimal, 18
Number("012"); // octal, 10

While this is true for parseInt as well, parseInt goes further. parseInt accepts parameters that start with a
string representation of a number.

parseInt("314abc"); // 314
Number("314abc"); // NaN

Boolean Primitive data types can be converted to Boolean using JavaScript’s built in Casting method,
‘Boolean()’.

var strString= "String";


document.write( Boolean(strString) );
//outputs: true -String has length greater than 1

var strString= "";


document.write( Boolean(strString) );
// outputs: false - String is empty.

var intNumber= 1;
document.write( Boolean(intNumber) );
// outputs: true - Integer greater than 1.
OPERATORS AND EXPRESSIONS
● Operators help perform an operation over data at runtime .
● Takes one or more arguments (operands)
● Produces a new value
● Operators have Precedence-Precedence defines which will be evaluated first and Associativity
Operators in JavaScript :
Unary – take one operand
Binary – take two operands
Ternary (?:) – takes three operands

Except for the assignment operators, all binary operators are left-associative
The assignment operators and the conditional operator (?:) are right-associative.

This example demonstrates how mathematical operations are carried out:


<Script language= “JavaScript/Text”>
number1=10
number2=8
sum=number1+number2
diff= number1-number2
product=number1*number2
quotient=number1/number2
document.write(number1+”+”+number2+”=”+sum+<br>)
document.write(number1+”-”+number2+”=”+diff+<br>)
document.write(number1+”x”+number2+”=”+product+<br>)
document.write(number1+”÷”+number2+”=”+quotient+<br>)
</Script>

The results are displayed below:


10+8=18
10-8=2
10x8=80
10÷8=1.25

<script language="javascript">
a=10
b=-10
c=b%3
a++
b--
document.write(a+"<br>")
document.write(b+"<br>")
document.write(c)
</script>

The output results are shown here


11
-11
-1
Relational/Comparison Operators
JavaScript support following comparison operators
Assume variable A holds 10 and variable B holds 20 then:
A college student has the following information in the college database
FirstNname: Ryan , LastName: John, StudentID: S2011, Age: 15, Attendance: 30, Class: 11

The following JavaScript statements produce true or false results.

Statement True/False
FirstName== ‘Ryan’ True
LastName==”George” False
StudentID==”S056” False
Attendance >20 True
FirstName!= “John” True
Age<12 False
Class>=10 True
Age<=20 True

// Type conversion is performed before comparison


var v1 = ("5" == 5); // true
// No implicit type conversion.
// True if only if both types and values are equal

var v2 = ("5" === 5); // false


var v3 = (5 === 5.0); // true
var v4 = (true == 1); // true (true is converted to 1)
var v5 = (true == 2); // false (true is converted to 1)
var v6 = (true == "1") // true

Logical Operators

Logical operators take boolean operands and return boolean result Operator ! turns true to false and false
to true Assume variable A holds 10 and variable B holds 20 then:
<html>
<head>
<title>Logical Operators</title>
</head>
<body>
<script language="javascript">
var age, height, entrancefee // optional
age= window.prompt("Enter your age:","0")
height= window.prompt("Enter your height:","0")
if (age>=12 || height>=140)// or operator
{entrancefee="$10"}
else
{entrancefee="$8"};
document.write("The entrance fee is: "+entrancefee);
</script>
</body>

Assignment Operators

JavaScript support following assignment operators


Assume variable A holds 10 and variable B holds 20 then:
Ternary/Conditional Operator

Conditional operators let JavaScript program executes certain jobs according to certain conditions. The
format of the conditional operator is:

Conditional Expression ? Execution 1: Execution 2


SYMBOL:
?:
The conditional operator comprises three parts:
● the first part is the conditional expression,
● the second part is execution 1
● and the last part is execution 2.

The question mark ? separates the conditional expression and execution 1 whilst the colon : separates
execution 1 and execution 2.
If the conditional expression is true, then JavaScript will run execution 1 and ignores execution2.
However, if the conditional expression is false, then JavaScript will ignore execution 1 and run
execution 2.
Therefore, the symbol ? and : completely replace If and Else.
typeof operator

The typeof 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. Type String Returned by typeof Number
"number" String "string" Boolean "boolean" Object "object" Function "function" Undefined "undefined"
Null "object" .
Other Operators

Member access operator . is used to access object members Square brackets [] are used with arrays
indexers and attributes Parentheses ( ) are used to override the default operator precedence The new
operator is used to create new objects This operator references the current context .
Expressions
Expressions are sequences of operators, literals and variables that are evaluated to some value

Examples:
var r = (150-20) / 2 + 5; // r=70
// Expression for calculation of circle area
var surface = Math.PI * r * r; // Expression for calculation of circle perimeter
var perimeter = 2 * Math.PI * r;

Decision making(CONDITIONAL STATEMENTS)

Decision making is the most important part of making any programming or scripting language
interactive. 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.

if/if-else
In JavaScript condition or logical expression is used with if-else. if-else statement provides a way to
change program flow based on a condition. We can have if statement without else but we cannot have
else without if.

Syntax 1:
if (condition)
{
statement / block
}

Syntax 2:
if (condition)
{
statement1 / block1
}
else
{
statement2 / block2
}

Syntax 3:
if (condition)
statement1
else if (condition)
statement2
else if (condition)
statement3
.
.
.
else
statement4
a) If the condition is TRUE then the statement1 or block1 is executed and the
statement or the block after the else is ignored.

b) If the condition is FALSE then the statement or block after the condition is
ignored and the statement2 or block2 is executed.

c) If there is no else, then statement immediately after if is executed.

•The condition can be:

✓Boolean variable
✓Boolean logical expression
✓Comparison expression
✓Integer, object, function... everything

•The condition can be of any type

•The statement can be:


✓Single statement ending with a semicolon
✓Block enclosed in braces
EXAMPLES:

<html>
<head>
</head>
<body>
<script language=“JavaScript">
mark=window.prompt("Enter mark:","0")
if(mark>=80)
document.write("Grade="+"A")
else
document.write("Grade="+“B")
</script>
</body>

Explanation of output: Inputted marks is 70, that is, variable marks has a value70.
if condition is tested (marks>=80), condition is FALSE. Therefore document.write("Grade="+“A")
is ignored and the statement after else, document.write("Grade="+“B") is executed.

<html>
<head>
<title>&& operator with if -else</title>
</head>
<body>
<script type="text/javascript">
a=window.prompt("Enter First
Angle”,"0");
b=window.prompt("Enter Second
Angle","0");
c=window.prompt("Enter Third
Angle","0");
if (a==60 && b ==60 && c ==60 )
alert(" Equiangular Triangle")
else
alert(" Not an Equiangular Triangle")
</script>
</body>
</html>
</html>

To check if the triangle is a right angled triangle


<html>
<head>
<title>&& operator with if -else</title>
</head>
<body>
<script type="text/javascript">
a=window.prompt("Enter First Angle”,"0");
b=window.prompt("Enter Second Angle","0");
c=window.prompt("Enter Third Angle","0");
if (a==90 || b ==90 || c ==90 )
alert(" Right angled Triangle")
else
alert(" Not a Right angled Triangle")
</script>
</body>
</html>
</html>

<html> <head>
<title> Using Nested if –else </title>
</head> <body>
<script type="text/javascript">
day=window.prompt("Enter Day[0-6]");
if (day == 0 )
alert ("Sunday") ;
else if (day == 1 )
{ alert ("Monday") ; }
else if (day == 2)
{ alert ("Tuesday") ; }
else if (day == 3)
{ alert ("Wednesday") ; }
else if (day == 4)
{ alert ("Thursday") ; }
else if (day == 5)
{ alert ("Friday") ; }
else if (day == 6)
{ alert ("Saturday") ; }
else { alert ("Error - invalid day.") ; }
</script>
</body> </html>

SWITCH CASE

Switch is a multiway decision maker

Syntax
switch (expression )
{ case value1 :
statement(s)
break ;
case value2 :
statement(s)
break ;
...
default :
statement(s)
break ; }

expression" is used to generate a test value that will be tested against with expected values
specified in "case" clauses. The execution of a "switch case"statement goes like this:
"case" clauses are possible execution starting points. Each "case" clause will be visited
sequentially from top to bottom. If the expected value of a "case" clause equals to the
test value resulted from the switch expression, the execution starts from those statements listed in
this "case" clause. Once the execution started, it will continue until a break statement is reached
or the end of the "switch" block is reached.
The "default" clause is optional. But if it is provided, it will become the execution starting point
when all case tests before the "default" clause are failed.

Eg: Input number of month and print the name of the month

<html> <head>
</head> <body>
<script language ="JavaScript">
month= parseInt(window.prompt("Enter Month[1-12]"))
switch(month)
{
case 1: alert("January")
break;
case 2: alert("February")
break;
case 3: alert("March")
break;
case 4: alert("April")
break;
case 5: alert("May")
break;
case 6: alert("June")
break;
case 7: alert("July")
break;
case 8: alert("August")
break;
case 9: alert("September")
break;
case 10: alert("October")
break;
case 11: alert("November")
break;
case 12: alert("December")
break;
default: alert ("Error - invalid month")
}
</script>
</body>
</html>
LOOPS-ITERATION

It is possible to repeat a statement or a block of statements.


JavaScript supports 3 types of loops:
● while loop
● for loop
● do–while loop

Generally any loop in JavaScript as three components:

a) Control Variable and its Initialisation: Generally a loop in JavaScript has a control
variable. Control variable is generally an integer type or character type or floating
point type. But we can have loop in JavaScriptwith out a control variable. We will
discuss such loops later. If a loop has a control variable then the control variable has
to be initialized.

b) Terminating Condition: Generally a loop should terminate after certain number


of iterations. Terminating condition of the loop in JavaScriptis a condition (logical
expression) involving the Control Variable. Condition or logical expression plays a
very important in the working of a loop in JavaScript since number of times loop is
repeated depends on the condition.

c) Updation of Control Variable: Every JavaScript loop repeats statement or block.


Inside the block or statement of a loop, control variable is updated (value of the
control variable is either incremented or decremented), so that the loop terminates
after certain number of iterations.

while loop: Loop through a set of statements as long as a condition is true:

Syntax
while(Condition)
{
JavaScript Statements;
Updating of control variable
before the close
}

The (condition) may be any JavaScript valid logical expression.

When program execution reaches a while statement, the following events occur:
1. The (condition) is evaluated.
2. Condition is TRUE (nonzero), the Block / Statement is executed.
3. Inside the Block / Statement, control variable is updated and Condition is tested once
These three steps are repeated till Condition is FALSE.
When the condition is evaluated to be false, the loop is terminates.
The while loop is an example of entry controlled loop, since first the Condition is
tested and then the Block or the Statement is executed.

do while: Loop through a set of statements as long as a condition is true but runs at least one
before checking condition

Syntax:
do
{
JavaScript Statements;
Updating of control variable
before the close
} while(Condition);

The loop runs once before (condition) Checking (condition) may be any JavaScript valid logical
expression.

When program execution reaches a do statement, the following events occur:


1. Inside the Block / Statement executed control variable is updated and then Condition is is
evaluated.
2. If Condition is TRUE (nonzero), the Block / Statement is executed again and process
repeated till Condition is FALSE.
3. When the condition is evaluated to be false, the loop is terminates.
The do-while loop is an example of Exit controlled loop, since Condition is tested
in last after once loop Block or the Statement is executed.

for loop - The for loop is almost similar to while loop but it is more compact than while
Loop.
The while loop has three important components:
an initialization of control variable, a terminating condition and update of control variable.

In a for loop all three components are together immediately after the keyword
for. A for loop is also an example of entry controlled loop.

Syntax:
for (Initialisation; Condition; Update)
Block / Statement;
for ( x = 1; x < 10 ; x = x + 1 )
{ document.write ( x ) ; }
For/In Loop - The JavaScript for/in statement loops through the properties of object:

Syntax
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
var person = {fname:"John", lname:"Doe", age:25};
var text = "";
var x;
for (x in person)
{ text += person[x];}
document. write(“Output will be :” +text) ;

Output will be : John Doe 25

You might also like