tags, JavaScript syntax like semicolons and case sensitivity, common data types like numbers and strings, variables, operators, and more. It provides examples of how to write JavaScript code and integrate it with HTML."> tags, JavaScript syntax like semicolons and case sensitivity, common data types like numbers and strings, variables, operators, and more. It provides examples of how to write JavaScript code and integrate it with HTML.">
[go: up one dir, main page]

0% found this document useful (0 votes)
26 views31 pages

Java Script

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 31

JavaScript

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

Attributes for script tag

 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.
 Type − This attribute is what is now recommended to
indicate the scripting language in use and its value should be
set to "text/javascript".

So your JavaScript will look like:

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


JavaScript code
</script>

JavaScript Syntax

document.write - writes a string into our HTML document.

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

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>

But when formatted in a single line as follows, you must use


semicolons

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


<!--
var1 = 10; var2 = 20;
//-->
</script>

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.

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

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 − Live Demo
<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

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.

Live Demo
<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

You can put your JavaScript code in <head> and <body> section
altogether as follows −

Live Demo
<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>

This code will produce the following result −

JavaScript in External File

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

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

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>

<script type = "text/javascript">


<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script>
JavaScript Reserved Words

A list of all the reserved words in JavaScript are given in the


following table. They cannot be used as JavaScript variables,
functions, methods, loop labels, or any object names.

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


+ (Addition)
1 Adds two operands
Ex: A + B will give 30
- (Subtraction)
2 Subtracts the second operand from the first
Ex: A - B will give -10
* (Multiplication)
3 Multiply both operands
Ex: A * B will give 200
/ (Division)
4 Divide the numerator by the denominator
Ex: B / A will give 2
% (Modulus)
5 Outputs the remainder of an integer division
Ex: B % A will give 0
++ (Increment)
6 Increases an integer value by one
Ex: A++ will give 11
-- (Decrement)
7 Decreases an integer value by one
Ex: A-- will give 9

Note − Addition operator (+) works for Numeric as well as Strings.


e.g. "a" + 10 will give "a10".

<html>
<body>

<script type = "text/javascript">


<!--
var a = 33;
var b = 10;
var c = "Test";
var linebreak = "<br />";
document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);

document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);

document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);

document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);

document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);

a = ++a;
document.write("++a = ");
result = ++a;
document.write(result);
document.write(linebreak);

b = --b;
document.write("--b = ");
result = --b;
document.write(result);
document.write(linebreak);
//-->
</script>

Set the variables to different values and then try...


</body>
</html>

Comparison Operators

JavaScript supports the following comparison operators −

Assume variable A holds 10 and variable B holds 20, then −

Sr.No. Operator & Description


= = (Equal)
Checks if the value of two operands are equal or not,
1
if yes, then the condition becomes true.
Ex: (A == B) is not true.
!= (Not Equal)
Checks if the value of two operands are equal or not,
2 if the values are not equal, then the condition
becomes true.
Ex: (A != B) is true.
> (Greater than)
Checks if the value of the left operand is greater
3 than the value of the right operand, if yes, then the
condition becomes true.
Ex: (A > B) is not true.
< (Less than)
Checks if the value of the left operand is less than
4 the value of the right operand, if yes, then the
condition becomes true.
Ex: (A < B) is true.
>= (Greater than or Equal to)
Checks if the value of the left operand is greater
5 than or equal to the value of the right operand, if yes,
then the condition becomes true.
Ex: (A >= B) is not true.
<= (Less than or Equal to)
Checks if the value of the left operand is less than or
6 equal to the value of the right operand, if yes, then
the condition becomes true.
Ex: (A <= B) is true.

<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
document.write("(a == b) => ");
result = (a == b);
document.write(result);
document.write(linebreak);
document.write("(a < b) => ");
result = (a < b);
document.write(result);
document.write(linebreak);
document.write("(a > b) => ");
result = (a > b);
document.write(result);
document.write(linebreak);
document.write("(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>
Set the variables to different values and different operators
and then try...
</body>
</html>
Logical Operators

Assume variable A holds 10 and variable B holds 20, then −

Sr.No. Operator & Description


&& (Logical AND)
If both the operands are non-zero, then the condition
1
becomes true.
Ex: (A && B) is true.
|| (Logical OR)
If any of the two operands are non-zero, then the
2
condition becomes true.
Ex: (A || B) is true.
! (Logical NOT)
Reverses the logical state of its operand. If a
3 condition is true, then the Logical NOT operator will
make it false.
Ex: ! (A && B) is false.

Live Demo
<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>

JavaScript - if...else Statement

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. Here we
will explain the if..else statement.

Flow Chart of if-else

The following flow chart shows how the if-else statement works.
JavaScript supports the following forms of if..else statement −

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

<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>
<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>
<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>
The while Loop

The most basic loop in JavaScript is the while loop which would
be discussed in this chapter. 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.
Flow Chart
The flow chart of while loop looks as follows −
Syntax
The syntax of while loop in JavaScript is as follows −
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>


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.

JavaScript supports all the necessary loops to ease down the


pressure of programming.

The while Loop

The most basic loop in JavaScript is the while loop which would
be discussed in this chapter. 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.
Flow Chart
The flow chart of while loop looks as follows −
Syntax
The syntax of while loop in JavaScript is as follows −
while (expression) {
Statement(s) to be executed if expression is true
}
Example

Try the following example to implement while loop.

Live Demo
<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.
Flow Chart
The flow chart of a do-while loop would be as follows −
Syntax
The syntax for do-while loop in JavaScript is as follows −
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>

JavaScript - For Loop

The 'for' loop is the most compact form of looping. It includes the
following three important parts −
 The loop initialization where we initialize our counter to a
starting value. The initialization statement is executed before
the loop begins.
 The test statement which will test if a given condition is true
or not. If the condition is true, then the code given inside the
loop will be executed, otherwise the control will come out of
the loop.
 The iteration statement where you can increase or
decrease your counter.

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

Flow Chart

The flow chart of a for loop in JavaScript would be as follows −


Syntax
The syntax of for loop is JavaScript is as follows −
for (initialization; test condition; iteration statement) {
Statement(s) to be executed if test condition is true
}
Example
Live Demo
<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>

JavaScript - Functions

A function is a group of reusable code which can be called


anywhere in your program. This eliminates the need of writing the
same code again and again. It helps programmers in writing
modular codes. Functions allow a programmer to divide a big
program into a number of small and manageable functions.

Function Definition

Before we use a function, we need to define it. The most common


way to define a function in JavaScript is by using
the function keyword, followed by a unique function name, a list
of parameters (that might be empty), and a statement block
surrounded by curly braces.
Syntax

The basic syntax is shown here.

<script type = "text/javascript">


<!--
function functionname(parameter-list) {
statements
}
//-->
</script>
Example

Try the following example. It defines a function called sayHello


that takes no parameters −

<script type = "text/javascript">


<!--
function sayHello() {
alert("Hello there");
}
//-->
</script>

Calling a Function

To invoke a function somewhere later in the script, you would


simply need to write the name of that function as shown in the
following code.

Live Demo
<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

Live Demo
<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('Zara', 7)" value =
"Say Hello">
</form>
<p>Use different parameters inside the function and then
try...</p>
</body>
</html>

You might also like