You are on page 1of 32

JAVASCRIPT : Introduction

JavaScript is an interpreted, client-side,


event-based, object-oriented scripting
language that you can use to add dynamic
interactivity to your web pages.

The language was invented by Brendan


Eich at Netscape (with Navigator 2.0) and
has appeared in all Netscape and Microsoft
browsers since 1996.

JavaScript is used in millions of Web pages


to:
add functionality,
validate forms,
detect browsers, and much more.

JavaScript is the most popular scripting


language on the Internet and works in all
major browsers, such as Internet Explorer,
Firefox, Chrome, Opera, and Safari.
JavaScript was designed to add
interactivity to HTML pages.
JavaScript is a scripting language.
A scripting language is a lightweight
programming language.
JavaScript is usually embedded directly
into HTML pages.

JavaScript can put dynamic text into an


HTML page. A JavaScript statement like
document.write(―<h1>‖ + name +
―</h1>‖) can write a variable text into an
HTML page.
JavaScript can react to events. A
JavaScript script can be set to execute
when something happens, like when a
page has finished loading or when a user
clicks on an HTML element.
JavaScript can read and write HTML
elements. A JavaScript script can readand
change the content of an HTML element.
 JavaScript can be used to validate data.
A JavaScript script can be used to validate
form data before it is submitted to a
server. This saves the server from extra
processing.
 JavaScript can be used to detect the
visitor‘s browser. A JavaScript script can
be used to detect the visitor‘s browser, and
depending on the browser, load another
page specifically designed for that
browser.
 JavaScript can be used to create cookies.
A JavaScript script can be used to store
and retrieve information on the visitor‘s
computer.

To insert a JavaScript into an HTML page,


we use the <script>tag. Inside
the<script>tag we use the type attribute
to define the scripting language.

So,
<script type="text/javascript">and
</script> tell where the Java-Script starts
and ends:
eg:
<html>
<body>
<script type="text/javascript">
...
</script>
</body>
</html>

Example:

<html>
<body>
<script type="text/javascript">
document.write("Happy, Happy,
Enjoy!");
</script>
</body>
</html>

The document.write command is a


standard JavaScript command for writing
output to a page.
When you type the document.write
command and between the <script>and
</script>tags, the browser will recognize
it as a JavaScript command and execute the
code line.

Advantages of JavaScript
Increased interactivity: You can
create interfaces that react when the user
hovers over them with a mouse or
activates them via the keyboard.

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

How to place the JS statements in the html


documents:
We can place <script> tag in <head>
section and JS statements can be placed
inside the <script> and </script> tags.

Example:

<head>
<script type=”text/javascript”>
JS statements go here…….
</script>
</head>

Here,
Type: attribute specifies scripting type.

Example:
<html>
<body>
<script language="javascript"
type="text/javascript">
<!--
document.write ("WEL-COME TO
JAVASCRIPT")
//-->
</script>
</body>
</html>

Case sensitivity:
JavaScript is a case-sensitive language. This
means that the language keywords,
variables, function names, and any other
identifiers must always be typed with a
consistent capitalization of letters.

So the identifiers Time and TIME will


convey different meanings in JavaScript.

Comments in JS:
 Single line comment: Any text between a
// and the end of line is treated as a
comment and is ignored by JS.
 Multi-line comment: The comments are
put between /* and */ .
 JS recognizes the html comment <!--
and //--> as comment.

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

Var a=6; // single line comment.


b=8*a/9; /* multiline comment in
JavaScript*/

</script>

JS Data types:
Data types are the types of values that can
be represented and manipulated in a
programming language.

There are three types of data types in JS:


 Numbers: eg: 1, 15, 23, 125, 123.25 etc.
 Strings of text : eg: ―The string text‖ etc.
 Boolean : eg: true or false.

Null and undefined are single valued data


type. An Object is a composite data type.
There is no distinction between integer and
float—all numbers in JS are represented as
floating point values.

JS variables:
Variables are named containers that hold
data values. We can place data into these
containers and then refer to the data simply
by naming the container.
Eg:

<script language=”Javascript”
type="text/javascript">
var address=”Attariya”;
var age;
age =35;

</script>
Use the var keyword only for declaration
or initialization.

JS Variable Scope:
The scope of a variable is the region of
program in which it is defined.

 Global variables: A global variable can


be defined anywhere in your JS code.

 Local variable: A local variable will be


visible only within a function where it is
defined. Function parameters are always
local to that function.

Within the body of a function, a local


variable takes precedence over a global
variable with the same name.

Eg:

<html>
<head>

</head>
<body onclick="checkscope()">

<script type="text/javascript">
var Var1 = "Globalvalue"; //global
variable

function checkscope(){
var Var1 = "localvalue"; // local
variable
document.write(Var1);
}
</script>
</body>
</html>

ESCAPE SEQUENCES:
A character in a string preceded by the
backslash (\) character is known as escape
sequence. This causes special effects on
character immediately following the
backslash.
The list of escape sequences:
\b Backspace
\f Form feed
\n New line
\r Carriage return
\‘ Single quote
\‖ Double quote
\\ Sing backslash character

JS Operators:
 Arithmetic operators
 Comparison operators
 Logical(or relational) operators
 Assignment operators
 Conditional(or ternary) operators

Arithmetic operators:
1. +( Addition) : Adds two operands.
Eg:- 3+9,
2. –(subtraction) : Subtracts the second
operand from the first
Ex: A - B
3. * (Multiplication) : Multiply both
operands. Eg: A * B
4. / (Division) : Divide the numerator
by the denominator. Ex: B / A
5. % (Modulus) : Outputs the remainder
of an integer division. Ex: B % A
6. ++ (Increment): Increases an integer
value by one. Ex: A++
7. -- (Decrement) : Decreases an integer
value by one. Ex: A—

Note: Addition operator (+) works for


Numeric as well as Strings. e.g. "a" + 10
will give "a10".

Eg:
<html>
<body>
<script type="text/javascript">
var a = 45;
var b = 6;
var c = "new_word";
document.write("a= ",a);
document.write("<br />");

document.write("b = ",b);
document.write("<br />");

document.write("a + b = ", a + b);

document.write("<br />"); //
cursor goes to new line ie.<br />

document.write("a % b = ");
modulus = a % b;
document.write(modulus); // the
result will be the remainder 3
document.write("<br />");

document.write("a + b + c = ");
addstring = a + b + c;
document.write(addstring);
//the result will be 51new_word
document.write("<br />");

a = a++;
document.write("a++ = ");
incremented_a = a++;
document.write(a);
document.write("<p>Here a=45 since
first assignment is done then
incremented</p>");
document.write("<br />");

document.write("a++=", a++);
document.write("<p> this line
increments a by 1 and displays it
</p>");
document.write("<br />");

</script>
<body>
</html>

Comparison Operators:
1. == (Equal) : Checks if the value
of two operands are equal or not,
if yes, then the condition becomes
true.
Ex: given A=9, B=6 then
(A == B) is not true.(i.e.false)
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: given A=9, B=6 then
(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: given A=9, B=6 then
(A > B) is 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 else false.
Ex: given A=9, B=6 then
(A < B) is false.
5. >= (Greater than or Equal to)
Checks if the value of the left
operand is greater than or equal
tothe value of the right operand, if
yes, then the condition becomes
true.
Ex: given A=9, B=6 then
(A >= B) is true. (i.e. at least
one condition is met)

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: given A=9, B=6 then
(A <= B) is not true.

Example:

<!DOCTYPE html>
<html>
<body>
<script language="Javascript"
type="text/javascript">

var p = 15;
var q = 30;
var breakline = "<br />";
document.write("(p == q) =>
");
res = (p == q);
document.write(res);
document.write(breakline);
document.write("(p < q) => ");
less = (p<q);
document.write(less);
document.write(breakline);

document.write("(p > q) => ");


grt = (p > q);
document.write(grt);
document.write(breakline);

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

Assignment Operators:
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

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

 ? : (Conditional )
If Condition is true?Then value X
:Otherwise value Y
Example:

<html>
<body>
<script type="text/javascript">

var a=200;
var b=100;

document.write("Here we have,
a=",a,"<br />");

document.write("Here we have,
b=",b,"<br />");

document.write ("((a > b) ? 100 :


200) => ");

result = (a > b) ? "a is greater"


: "b is greater";
document.write(result);
</script>

</body>
</html>
IF Condition:
A JS expression is evaluated–if the
condition is true then the given statements
are executed. If condition fails(appears
false) then no statement is executed.
Syntax:
if (expression){
Statement(s) to be executed if
expression is true
}

IF-ELSE condition:
A JS expression is evaluated–if the
condition is true then the given statements
are executed. If condition fails(appears
false) then statements in else block are
executed.
Syntax:
if (expression){
Statement(s) to be executed if
expression is true
}else{
Statement(s) to be executed if
expression is false
}
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
}
elseif (expression 2)
{ Statement(s) to be executed if
expression 2 is true
}
elseif (expression 3)
{ Statement(s) to be executed if
expression 3 is true
}
else
{ Statement(s) to be executed if
no expression is true
}
SWITCH CASE:
A switch statement is to give an expression
to evaluate several different statements to
execute based on the value of the
expression.

Syntax:
switch (expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}

The break statements indicate the end of a


particular case. If they were
omitted, the interpreter would continue
executing each statement in each of the
following cases.
Example:
<html>
<body>
<script type="text/javascript">
<!--
var grade;
grade=prompt("Enter the grade",
grade);

switch (grade)
{
case 'A' : document.write("A GRADE
!! EXCELLENT !!!<br />");
break;
case 'B': document.write("B GRADE
!! GOOD !!!<br />");
break;
case 'C': document.write("Passed
!! Work Hard<br />");
break;
case 'D': document.write("NOT SO
GOOD....TRY HARDER<br />");
break;
case 'F': document.write("OOps !
Failed... TRY AGAIN<br />");
break;
default: document.write("UNKNOWN
GRADE ....<br />")
}

//-->
</script>
</body>
</html>

The while Loop

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

Example:

<html>
<body>

<script type="text/javascript">
<!--
var count = 0;
;document.write("Starting Loop ");
document.write("<br />");
while (count <= 10){
document.write("Current Count : "
+ count + "<br />");
count++;
}
document.write("<br />");
document.write("Loop stopped!");
//-->
</script>

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

Example:
<html>
<body>
<script type="text/javascript">
<!--
var count = 0;

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

//-->
</script>

</body>
</html>

THE BREAK STATEMENT :

BREAK STATEMENT is used to exit a


loop early, breaking out of the enclosing
curly braces.

<html>
<body>
<script
type="text/javascript">
<!--
var x = 1;

while (x < 20)


{
if (x == 9)
{
break; /* breaks out
of while loop*/
}
x = x + 1;
document.write( x + "<br
/>");
}

//-->
</script>

</body>
</html>

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

Note: simply, the functions are kept in


<head> section and can be called from any
where.

Example:
<script type="text/javascript">
<!--
function Hello()
{
Document.write(“Hello there, How
are you?");
}
//-->
</script>

Calling a function:

Example:

<html>
<head>
<script type="text/javascript">
function Hello()
{
var name;
var age;
name=prompt("Enter the
name",name);
age=prompt("Enter the age",age);
document.write (name + " is " +
age + " years old.");
}
</script>
</head>

<body>
<form>
<input type="button"
onclick="Hello()" value="Hello-
ClickHERE">
</form>
</body>
</html>

You might also like