Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
12 views

Javascript-Unit-3

Uploaded by

sundar chhetri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Javascript-Unit-3

Uploaded by

sundar chhetri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 137

JAVA SCRIPT

UNIT III : Java Script


3.1 Java Script

 JavaScript was initially created to “make web pages alive”.


 The programs in this language are called scripts.
 They can be written right in a web page’s HTML and executed
automatically as the page loads.
 Scripts are provided and executed as plain text. They don’t
need special preparation or compilation to run.
 In this aspect, JavaScript is very different from another
language called Java.
 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.
 avaScript 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.
Why JavaScript?
 When JavaScript was created, it initially had
another name: “LiveScript”. But Java was very
popular at that time, so it was decided that
positioning a new language as a “younger brother”
of Java would help.
 But as it evolved, JavaScript became a fully
independent language with its own specification
called ECMAScript, and now it has no relation to
Java at all.
 Today, JavaScript can execute not only in the
browser, but also on the server, or actually on any
device that has a special program called the
JavaScript engine.
 The browser has an embedded engine sometimes
called a “JavaScript virtual machine”.
 Different engines have different “codenames”. For
example:
 V8 – in Chrome and Opera.
 SpiderMonkey – in Firefox.
How do engines work?
 Engines are complicated. But the basics are easy.
 The engine (embedded if it’s a browser) reads
(“parses”) the script.
 Then it converts (“compiles”) the script to the machine
language.
 And then the machine code runs, pretty fast.
 The engine applies optimizations at each step of the
process.
 It even watches the compiled script as it runs, analyzes
the data that flows through it, and applies optimizations
to the machine code based on that knowledge. When
it’s done, scripts run quite fast.
What makes JavaScript unique?
 Full integration with HTML/CSS.
 Simple things are done simply.
 Support by all major browsers and enabled by
default.
Advantages of JavaScript
 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.
 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
 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.
JavaScript Development Tools
 Microsoft FrontPage − Microsoft has developed a popular
HTML editor called FrontPage. FrontPage also provides web
developers with a number of JavaScript tools to assist in the
creation of interactive websites.
 Macromedia Dreamweaver MX − Macromedia
Dreamweaver MX is a very popular HTML and JavaScript
editor in the professional web development crowd. It
provides several handy prebuilt JavaScript components,
integrates well with databases, and conforms to new
standards such as XHTML and XML.
 Macromedia HomeSite 5 − HomeSite 5 is a well-liked HTML
and JavaScript editor from Macromedia that can be used to
manage personal websites effectively.
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 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>
Your First JavaScript Code
 <html>
 <body>
 <script language = "javascript" type =
"text/javascript">
 <!-- document.write("Hello World!") //-->
</script>
 </body>
 </html>
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 in a neat and consistent way
that makes the code easy to read and understand.
Semicolons are Optional
 Simple statements in JavaScript are generally
followed by a semicolon character, just as they are
in C, C++, and Java.
 JavaScript, however, allows you to omit this
semicolon if 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">
 <!-- var1 = 10
 var2 = 20 //-->
 </script>

 <script language = "javascript" type = "text/javascript">


 <!-- var1 = 10;
 var2 = 20; //-->
 </script>
 Note − It is a good programming practice to use
semicolons.
Case Sensitivity
 JavaScript is a case-sensitive language.
 This means that 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.
 NOTE − Care should be taken while writing
variable and function names 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.
 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
 <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>
Enabling JavaScript in Browsers
 All the modern browsers come with built-in support
for JavaScript.
 Frequently, you may need to enable or disable this
support manually.
 This chapter explains the procedure of enabling
and disabling JavaScript support in your browsers:
Internet Explorer, Firefox, chrome, and Opera.
JavaScript in 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
 To disable JavaScript support in your Internet
Explorer, you need to select Disable radio button
under Active scripting.
JavaScript in Chrome
 Click the Chrome menu at the top right hand corner
of your browser.
 Select Settings.
 Click Show advanced settings at the end of the
page.
 Under the Privacy section, click the Content settings
button.
 In the "Javascript" section, select "Do not allow any
site to run JavaScript" or "Allow all sites to run
JavaScript (recommended)".
Warning for Non-JavaScript Browsers

 <html> <body>
 <script language = "javascript" type =
"text/javascript">
 <!-- document.write("Hello World!") //-->
 </script>
 <noscript> Sorry...JavaScript is needed to go
ahead. </noscript>
 </body>
 </html>
JavaScript - Placement in HTML File
 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.
JavaScript in <head>...</head> section

 <html> <head>
 <script type = "text/javascript">
 <!-- function sayHello() { alert("Hello World") } //-->
 </script>
 </head> <body>
 <input type = "button" onclick = "sayHello()" value =
"Say Hello" />
 </body>
 </html>
JavaScript in <body>...</body> section

 <html> <head> </head>


 <body>
 <script type = "text/javascript"> <!--
document.write("Hello World") //-->
 </script>
 <p>This is web page body </p>
 </body>
 </html>
JavaScript in <body> and <head> Sections

 <html> <head>
 <script type = "text/javascript">
 <!-- function sayHello() {
 alert("Hello World") } //--> </script>
 </head> <body>
 <script type = "text/javascript">
 <!-- document.write("Hello World") //-->
 </script>
 <input type = "button" onclick = "sayHello()" value = "Say
Hello" />
 </body> </html>
JavaScript in External File
 <html> <head>
 <script type = "text/javascript" src = "filename.js" >
 </script>
 </head>
 <body> ....... </body>
 </html>
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, eg. 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 − JavaScript 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;
Storing a value in a variable is called
//--> variable initialization.
</script> 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 money, name; <script type = "text/javascript">
//--> <!–
var name = "Ali";
</script>
var money; money = 2000.50;
//-->
</script>
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. Function
parameters are always local to that function.
<html>
<body onload = checkscope();>
<script type = "text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
//-->
</script>
</body>
</html>
JavaScript Variable Names
 While naming your variables in JavaScript, keep the
following rules in mind.
 You should not use any of the JavaScript reserved keywords
as a variable name. These keywords are mentioned in the
next section. For example, break or boolean variable names
are not valid.
 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.
 JavaScript variable names are case-sensitive. For
example, Name and name are two different variables.
JavaScript Reserved Words
abstract else instanceof switch
boolean enum int synchronized
break export interface this
byte extends long throw
case false native throws
catch final new transient
char finally null true
class float package try
const for private typeof
continue function protected var
debugger goto public void
default if return volatile
delete implements short while
do import static with
double in super
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
Arithmetic Operators
 JavaScript supports the following arithmetic
operators −
 Assume variable A holds 10 and variable B holds
20, then −
Sr.No. Operator & Description
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
<html>
<body> document.write("a + b + c = ");
<script type = "text/javascript"> result = a + b + c;
<!– document.write(result);
var a = 33; document.write(linebreak);
var b = 10; a = ++a;
var c = "Test"; document.write("++a = ");
var linebreak = "<br />"; result = ++a;
document.write("a + b = "); document.write(result);
result = a + b; document.write(result); document.write(linebreak);
document.write(linebreak); b = --b;
document.write("a - b = "); document.write("--b = ");
result = a - b; result = --b;
document.write(result); document.write(result);
document.write(linebreak); document.write(linebreak);
document.write("a / b = "); //-->
result = a / b; </script>
document.write(result); Set the variables to different values and then try...
document.write(linebreak); </body>
document.write("a % b = "); </html>
result = a % b; document.write(result);
document.write(linebreak);
Comparison Operators
 JavaScript supports the following comparison
operators −
 Assume variable A holds 10 and variable B holds
20, then −
Sr.No. Operator & Description
1 = = (Equal)
Checks if the value of two operands are equal or not, if yes, then the condition
becomes true.
Ex: (A == B) is not true.
2 != (Not Equal)
Checks if the value of two operands are equal or not, if the values are not
equal, then the condition becomes true.
Ex: (A != B) is true.
3 > (Greater than)
Checks if the value of the left operand is greater than the value of the right
operand, if yes, then the condition becomes true.
Ex: (A > B) is not true.
4 < (Less than)
Checks if the value of the left operand is less than the value of the right
operand, if yes, then the condition becomes true.
Ex: (A < B) is true.
5 >= (Greater than or Equal to)
Checks if the value of the left operand is greater than or equal to the value
of the right operand, if yes, then the condition becomes true.
Ex: (A >= B) is not true.
6 <= (Less than or Equal to)
Checks if the value of the left operand is less than or equal to the value of
the right operand, if yes, then the condition becomes true.
Ex: (A <= B) is true.
<html>
<body> document.write(result);
<script type = "text/javascript"> document.write(linebreak);
<!– document.write("(a >= b) => ");
var a = 10; result = (a >= b);
var b = 20; document.write(result);
var linebreak = "<br />"; document.write(linebreak);
document.write("(a == b) => "); document.write("(a <= b) => ");
result = (a == b); result = (a <= b);
document.write(result); document.write(result);
document.write(linebreak); document.write(linebreak);
document.write("(a < b) => "); //-->
result = (a < b); </script>
document.write(result); Set the variables to different values and different
document.write(linebreak); operators and then try...
document.write("(a > b) => "); </body>
result = (a > b); </html>
document.write(result);
document.write(linebreak);
document.write("(a != b) => ");
result = (a != b);
Logical Operators
 JavaScript supports the following logical operators −
 Assume variable A holds 10 and variable B holds 20,
then −
Sr.No. Operator & Description
1 && (Logical AND)
If both the operands are non-zero, then the condition becomes true.
Ex: (A && B) is true.
2 || (Logical OR)
If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.
3 ! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the Logical
NOT operator will make it false.
Ex: ! (A && B) is false.
<html>
<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>
<p>Set the variables to different values and different operators and then try...</p>
</body> </html>
Bitwise Operators
 JavaScript supports the following bitwise operators
 Assume variable A holds 2 and variable B holds 3, then
Sr.No. Operator & Description
1 & (Bitwise AND)
It performs a Boolean AND operation on each bit of its integer arguments.
Ex: (A & B) is 2.
2 | (BitWise OR)
It performs a Boolean OR operation on each bit of its integer arguments.
Ex: (A | B) is 3.
3 ^ (Bitwise XOR)
It performs a Boolean exclusive 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.
Ex: (A ^ B) is 1.
4 ~ (Bitwise Not)
It is a unary operator and operates by reversing all the bits in the operand.
Ex: (~B) is -4.
5 << (Left Shift)
It moves all the bits in its first 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.
Ex: (A << 1) is 4.
6 >> (Right Shift)
Binary Right Shift Operator. The left operand’s value is moved right by the
number of bits specified by the right operand.
Ex: (A >> 1) is 1.
7 >>> (Right shift with Zero)
This operator is just like the >> operator, except that the bits shifted in on the
left are always zero.
Ex: (A >>> 1) is 1.
<html>
document.write(linebreak);
<body>
document.write("(a << b) => ");
<script type = "text/javascript">
result = (a << b);
<!–
document.write(result);
var a = 2; // Bit presentation 10
document.write(linebreak);
var b = 3; // Bit presentation 11
document.write("(a >> b) => ");
var linebreak = "<br />";
result = (a >> b);
document.write("(a & b) => ");
document.write(result);
result = (a & b);
document.write(linebreak);
document.write(result);
//-->
document.write(linebreak);
</script>
document.write("(a | b) => ");
<p>Set the variables to different values and
result = (a | b);
different operators and then try...</p>
document.write(result);
</body>
document.write(linebreak);
</html>
document.write("(a ^ b) => ");
result = (a ^ b);
document.write(result);
document.write(linebreak);
document.write("(~b) => ");
result = (~b);
document.write(result);
Assignment Operators
Sr.No. Operator & Description
1 = (Simple Assignment )
Assigns values from the right side operand to the left side operand
Ex: C = A + B will assign the value of A + B into C

2 += (Add and Assignment)


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

3 −= (Subtract and Assignment)


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

4 *= (Multiply and Assignment)


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

5 /= (Divide and Assignment)


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

6 %= (Modules and Assignment)


It takes modulus using two operands and assigns the result to the left operand.
Ex: C %= A is equivalent to C = C % A
<html>
<body> document.write(linebreak);
<script type = "text/javascript"> document.write("Value of a => (a /= b) => ");
<!– result = (a /= b); document.write(result);
var a = 33; document.write(linebreak);
var b = 10; document.write("Value of a => (a %= b) => ");
var linebreak = "<br />"; result = (a %= b); document.write(result);
document.write("Value of a => (a = b) => "); document.write(linebreak);
result = (a = b); //-->
document.write(result); </script>
document.write(linebreak); <p>Set the variables to different values and
document.write("Value of a => (a += b) => ");different operators and then try...</p>
result = (a += b); </body>
document.write(result); </html>
document.write(linebreak);
document.write("Value of a => (a -= b) => ");
result = (a -= b);
document.write(result);
document.write(linebreak);
document.write("Value of a => (a *= b) => ");
result = (a *= b); document.write(result);
Miscellaneous Operator
 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.
Sr.No. Operator and Description
1 ? : (Conditional )
If Condition is true? Then value X : Otherwise value Y
<html>
<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>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
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"
<html>
<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>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
JavaScript supports the following forms
of if..else statement −
 if statement
 if...else statement
 if...else if... statement.
if statement
 The if statement is the fundamental control
statement that allows JavaScript to make decisions
and execute statements conditionally.
 Syntax
 The syntax for a basic if statement is as follows −
if (expression) {
Statement(s) to be executed if expression is true
}
<html>
<body>
<script type = "text/javascript">
<!–
var age = 20;
if( age > 18 ) {
document.write("<b>Qualifies for driving</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
if...else statement
 The 'if...else' statement is the next form of control
statement that allows JavaScript to execute statements
in a more controlled way.
 Syntax
if (expression) {
Statement(s) to be executed if expression is true
}
else {
Statement(s) to be executed if expression is false
}
<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>
<p>Set the variable to different value and then try...</p>
</body>
</html>
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
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
}
<html>
<body>
<script type = "text/javascript">
<!–
var book = "maths";
if( book == "history" ) {
document.write("<b>History Book</b>");
} else if( book == "maths" ) {
document.write("<b>Maths Book</b>");
} else if( book == "economics" ) {
document.write("<b>Economics Book</b>");
} else {
document.write("<b>Unknown Book</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
<html>
Switch Statement
 Starting with JavaScript 1.2, you can use
a switch statement which handles exactly this situation,
and it does so more efficiently than repeated if...else
ifstatements.
 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) {
case condition 1: statement(s)
break;
case condition 2: statement(s)
break; ...
------
------
------
case condition n: statement(s)
break;
default: statement(s)
}
<html>
<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>
<p>Set the variable to different value and then try...</p>
</body> </html>
Loop
 While loop
 Do – while loop
 For loop
 For in loop
The while Loop
 The most basic loop in JavaScript is 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
}
<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>
The do...while Loop
 The do...while loop is similar to the while loop
except that the condition check happens at the end
of the loop.
 This means that the loop will always be executed at
least once, even if the condition is false.
 Syntax

do {
Statement(s) to be executed;
} while (expression);
<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!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
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.
 Syntax
for (initialization; test condition; iteration statement)
{
Statement(s) to be executed if test condition is true
}
<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>
For in loop
 The for...in loop is used to loop through an object's
properties.
 As we have not discussed Objects yet, you may not feel
comfortable with this loop. But once you understand how
objects behave in JavaScript, you will find this loop
very useful.
 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
 Try the following example to implement ‘for-in’ loop.
It prints the web browser’s Navigator object.
<html>
<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>
<p>Set the variable to different object and then try...</p>
</body>
</html>
Loop Control
 JavaScript provides full control to handle loops and
switch statements. There may be a situation when you
need to come out of a loop without reaching its bottom.
There may also be a situation when you want to skip a
part of your code block and start the next iteration of
the loop.
 To handle all such situations, JavaScript
provides break and continue statements. These
statements are used to immediately come out of any
loop or to start the next iteration of any loop
respectively.
The break Statement
 The break statement, which was briefly introduced
with the switch statement, is used to exit a loop
early, breaking out of the enclosing curly braces.
<html>
<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 }
x = x + 1;
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
The continue Statement
 The continue statement tells the interpreter to
immediately start the next iteration of the loop and
skip the remaining code block. When
a continuestatement is encountered, the program
flow moves to the loop check expression
immediately and if the condition remains true, then
it starts the next iteration, otherwise the control
comes out of the loop.
 Example
<html>
<body>
<script type = "text/javascript">
<!–
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 10) {
x = x + 1;
if (x == 5) {
continue; // skip rest of the loop body
}
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Using Labels to Control the Flow
 Starting from JavaScript 1.2, a label can be used
with break and continue to control the flow more
precisely. A label is simply an identifier followed by a
colon (:) that is applied to a statement or a block of
code. We will see two different examples to
understand how to use labels with break and continue.
 Note − Line breaks are not allowed between
the ‘continue’ or ‘break’statement and its label name.
Also, there should not be any other statement in
between a label name and associated loop.
<html>
<body>
<script type = "text/javascript">
<!–
document.write("Entering the loop!<br /> ");
outerloop: // This is the label name
for (var i = 0; i < 5; i++) {
document.write("Outerloop: " + i + "<br />");
innerloop:
for (var j = 0; j < 5; j++) {
if (j > 3 ) break ; // Quit the innermost loop
if (i == 2) break innerloop; // Do the same thing
if (i == 4) break outerloop; // Quit the outer loop
document.write("Innerloop: " + j + " <br />");
}
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
</body>
</html>
Array
 The Array object lets you store multiple values in a
single variable.
 It stores a fixed-size sequential collection of elements of
the same type.
 An array is used to store a collection of data, but it is
often more useful to think of an array as a collection of
variables of the same type.
 Syntax
 Use the following syntax to create an Array object −
 var fruits = new Array( "apple", "orange", "mango" );
 The Array parameter is a list of strings or integers.
When you specify a single numeric parameter with
the Array constructor, you specify the initial length
of the array. The maximum length allowed for an
array is 4,294,967,295.
 You can create array by simply assigning values as
follows −
 var fruits = [ "apple", "orange", "mango" ];
 var points = new Array(40, 100, 1, 5, 25, 10);
var points = [40, 100, 1, 5, 25, 10];
Array Properties
Sr. No. Property & Description
1 constructorReturns a reference to the array function that created
the object.
2 index
The property represents the zero-based index of the match in the
string
3 input
This property is only present in arrays created by regular
expression matches.
4 lengthReflects the number of elements in an array.
5 prototypeThe prototype property allows you to add properties and
methods to an object.
Function
 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.
 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
<script type = "text/javascript">
<!–
function functionname(parameter-list) {
statements
}
//-->
</script>
Example
<script type = "text/javascript">
<!- -
function sayHello() {
alert("Hello there");
}
//-->
</script>
Calling a Function
<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>
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.
<html>
<head>
<script type = "text/javascript">
function sayHello(name, age) {
document.write (name + " is " + age + " years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello(‘Sulove', 39)" value = "Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
The return Statement
 A JavaScript function can have an
optional return statement. This is required if you
want to return a value from a function. This
statement should be the last statement in a function.
 For example, you can pass two numbers in a
function and then you can expect the function to
return their multiplication in your calling program.
<html>
<head>
<script type = "text/javascript">
function concatenate(first, last) {
var full; full = first + last; return full;
}
function secondFunction() {
var result;
result = concatenate('Zara', 'Ali');
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>
Event
 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 too is an event. Other examples
include events like pressing any key, closing a window,
resizing a window, etc.
 Developers can use these events to execute JavaScript
coded responses, which cause buttons to close windows,
messages to be displayed to users, data to be validated,
and virtually any other type of response imaginable.
 Events are a part of the Document Object Model (DOM)
Level 3 and every HTML element contains a set of events
which can trigger JavaScript Code.
onclick Event Type
 This is the most frequently used event type which
occurs when a user clicks the left button of his
mouse. You can put your validation, warning etc.,
against this event type.
<html>
<head>
<script type = "text/javascript">
<!–
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</form>
</body>
</html>
onsubmit Event Type
 onsubmit is an event that occurs when you try to
submit a form. You can put your form validation
against this event type.
 Example
 The following example shows how to use onsubmit.
Here we are calling a validate() function before
submitting a form data to the webserver.
If validate() function returns true, the form will be
submitted, otherwise it will not submit the data.
<html>
<head>
<script type = "text/javascript">
<!–
function validation() {
all validation goes here ......... return either true or false
}
//-->
</script>
</head>
<body>
<form method = "POST" action = "t.cgi" onsubmit = "return validate()">
....... <input type = "submit" value = "Submit" />
</form>
</body>
</html>
onmouseover and onmouseout
 These two event types will help you create nice
effects with images or even with text as well.
The onmouseover event triggers when you bring
your mouse over any element and
the onmouseout triggers when you move your
mouse out from that element. Try the following
example.
<html>
<head>
<script type = "text/javascript">
<!–
function over() {
document.write ("Mouse Over");
}
function out() {
document.write ("Mouse Out");
}
//-->
</script>
</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover = "over()" onmouseout = "out()">
<h2> This is inside the division </h2>
</div>
</body> https://www.tutorialspoint.com/javascript/javascript_events.htm
</html>
 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.
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;
 var str = document.title;
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");
User-Defined Objects
 All user-defined objects and built-in objects are
descendants of an object called Object.
 The new Operator
 The new operator is used to create an instance of
an object. To create an object, the new operator is
followed by the constructor method.
 In the following example, the constructor methods
are Object(), Array(), and Date(). These constructors
are built-in JavaScript functions.
 var employee = new Object();
 var books = new Array("C++", "Perl", "Java");
 var day = new Date("August 15, 1947");
 The Object() Constructor
 A constructor is a function that creates and initializes
an object. JavaScript provides a special constructor
function called Object() to build the object. The
return value of the Object() constructor is assigned
to a variable.
 The variable contains a reference to the new object.
The properties assigned to the object are not
variables and are not defined with
the var keyword.
<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>
<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>
Defining Methods for an Object
 The previous examples demonstrate how the
constructor creates the object and assigns
properties. But we need to complete the definition
of an object by assigning methods to it.
<html>
<head>
<title>User-defined objects</title> </script>
<script type = "text/javascript"> </body>
// Define a function which will work as a method function </html>
addPrice(amount) {
this.price = amount;
}
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>");
The 'with' Keyword
 The ‘with’ keyword is used as a kind of shorthand
for referencing an object's properties or methods.
 The object specified as an argument
to with becomes the default object for the duration
of the block that follows. The properties and
methods for the object can be used without naming
the object.
 Syntax
 The syntax for with object is as follows −
 with (object) {
properties used without the object name and dot
}
<html>
<head>
<title>User-defined objects</title>
<script type = "text/javascript">
// Define a function which will work as a method function
addPrice(amount) {
with(this) { myBook.addPrice(100);
price = amount; document.write("Book title is : " + myBook.title + "<br>");
} document.write("Book author is : " + myBook.author + "<br>");
} document.write("Book price is : " + myBook.price + "<br>");
function book(title, author) { </script>
this.title = title; </body>
this.author = author; </html>
this.price = 0;
this.addPrice = addPrice;
// Assign that method as property.
}
</script>
</head>
<body>
<script type = "text/javascript">
var myBook = new book("Perl", "Mohtashim");
Getting data from Form and form
validation
 Form validation normally used to occur at the server,
after the client had entered all the necessary data and
then pressed the Submit button. If the data entered by
a client was incorrect or was simply missing, the server
would have to send all the data back to the client and
request that the form be resubmitted with correct
information. This was really a lengthy process which
used to put a lot of burden on the server.
 JavaScript provides a way to validate form's data on
the client's computer before sending it to the web
server.
Form validation generally performs
two functions.
 Basic Validation − First of all, the form must be
checked to make sure all the mandatory fields are
filled in. It would require just a loop through each
field in the form and check for data.
 Data Format Validation − Secondly, the data that
is entered must be checked for correct form and
value. Your code must include appropriate logic to
test correctness of data.
<html>
<head>
<title>Form Validation</title>
<script type = "text/javascript">
<!–
// Form validation code will come here.
//-->
</script>
</head>
<body>
<form action = "/cgi-bin/test.cgi" name = "myForm" onsubmit = "return(validate());">
<table cellspacing = "2" cellpadding = "2" border = "1">
<tr>
<td align = "right">Name</td>
<td><input type = "text" name = "Name" /></td>
</tr>
<tr>
<td align = "right">EMail</td>
<td><input type = "text" name = "EMail" /></td>
</tr>
<tr>
<td align = "right">Zip Code</td>
<td><input type = "text" name = "Zip" /></td>
</tr>
<tr>
<td align = "right">Country</td>
<td> <select name = "Country">
<option value = "-1" selected>[choose yours] </option>
<option value = "1">USA</option>
<option value = "2">UK</option>
<option value = "3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align = "right"></td>
<td><input type = "submit" value = "Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
Basic Form Validation
 First let us see how to do a basic form validation. In
the above form, we are calling validate() to
validate data when onsubmit event is occurring.
The following code shows the implementation of this
validate() function.
<script type = "text/javascript">
<!-- // Form validation code will come here.
function validate() {
if( document.myForm.Name.value == "" ) {
alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
} if( document.myForm.EMail.value == "" ) {
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
} if( document.myForm.Zip.value == "" || isNaN( document.myForm.Zip.value )
|| document.myForm.Zip.value.length != 5 ) {
alert( "Please provide a zip in the format #####." );
document.myForm.Zip.focus() ; return false;
} if( document.myForm.Country.value == "-1" ) {
alert( "Please provide your country!" );
return false;
}
return( true );
}
//-->
</script>
Data Format Validation
 Now we will see how we can validate our entered
form data before submitting it to the web server.
 The following example shows how to validate an
entered email address. An email address must
contain at least a ‘@’ sign and a dot (.). Also, the
‘@’ must not be the first character of the email
address, and the last dot must at least be one
character after the ‘@’ sign.
 Example
 Try the following code for email validation.
<script type = "text/javascript">
<!–
function validateEmail() {
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 )) {
alert("Please enter correct email ID") document.myForm.EMail.focus() ;
return false;
}
return( true );
}
//-->
</script>
Concept of JQUERY
 jQuery is a lightweight, "write less, do more",
JavaScript library.
 The purpose of jQuery is to make it much easier to
use JavaScript on your website.
 jQuery takes a lot of common tasks that require
many lines of JavaScript code to accomplish, and
wraps them into methods that you can call with a
single line of code.
jQuery library features:
 HTML/DOM manipulation
 CSS manipulation
 HTML event methods
 Effects and animations
 AJAX
 Utilities

 jQuery will run exactly the same in all major


browsers.
Adding jQuery to Your Web Pages
 There are several ways to start using jQuery on
your web site. You can:
 Download the jQuery library from jQuery.com
 Include jQuery from a CDN, like Google

Downloading jQuery
 There are two versions of jQuery available for
downloading:
 Production version - this is for your live website
because it has been minified and compressed
 Development version - this is for testing and
development (uncompressed and readable code)
 Both versions can be downloaded from jQuery.com.
 http://jquery.com/download/
 The jQuery library is a single JavaScript file, and
you reference it with the HTML <script> tag (notice
that the <script> tag should be inside
the <head> section):

 <head>
<script src="jquery-3.4.0.min.js"></script>
</head>
jQuery CDN
 f you don't want to download and host jQuery
yourself, you can include it from a CDN (Content
Delivery Network).
 Both Google and Microsoft host jQuery.
 To use jQuery from Google or Microsoft, use one of
the following:
Google CDN:
 <head>
<script src="https://ajax.googleapis.com/ajax/libs
/jquery/3.4.0/jquery.min.js"></script>
</head>
Microsoft CDN:
 <head>
 <script src="https://ajax.aspnetcdn.com/ajax/jQu
ery/jquery-3.4.0.min.js">
 </script>
 </head>
 Go through below reference link for more
knowledge
Reference
 https://javascript.info/
 https://www.tutorialspoint.com/javascript/javascrip
t_enabling.htm
 https://www.w3schools.com/jquery/default.asp

You might also like