Class - 12/we App-Notes - Javascript

You might also like

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

Java Script Notes

Scripting language and how is it different from Programming language


A scripting language is a programming language designed for integrating and communicating with other
programming languages. Some of the most widely used scripting languages are JavaScript, VBScript, PHP,
Perl.
Scripting language Programming language
A scripting language is normally used in A programming language is a set of commands,
conjunction with another programming instructions, and other syntax use to create a
language, they are often found alongside HTML software program. Languages that programmers use
to write code are called "high-level languages"
They use implicit variable declaration They use explicit variable declaration
A scripting languages do not require the The system does not accept this HLL so the compiler
compilation step and are rather interpreted by helps by converting these HLL into machine
the browser and so there is no need of a languages. They interpret line by line inorder to
compiler execute a task.
Execution time is less Execution time is more

Java Script - its features and limitations


It is widely supported cross platform object oriented client side scripting language developed by Netscape.
When incorporated with HTML, it makes the HTML programming a dynamic one. It is available with following
browsers :
o Netscape Navigator
o Firefox
o Google Chrome
o Internet Explorer etc.
Features :
 Displays messages to the user in the browser's status line or in alert boxes
 Validates the contents of the form
 Animates the images with mouse roll over etc
 Creates ad banners
 Detects the browser in use and perform advanced functions
 Detects installed plug-ins(Active-X controls)
 Modifies all or part of the webpage
 Displays and interact with user input.
 JavaScript is a dynamic or loosely-typed language because a variable can hold value of any data type
at any point of time.

Limitations :
 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 multithreading or multiprocessor capabilities
Difference between Client Side Scripting Language and Server Side Scripting Language

Client Side Scripting language Server Side Scripting language


A Client Side Scripting language works at the A Server Side Scripting language works in the back
front end and script are visible among the users. end which could not be visible at the client end.
For processing does not require server For processing requires server interaction and hence
interaction and hence can be executed from any for execution the stand alone machine must be
standalone machine. converted to server machine
Insecure Relatively secure
Browser interprets both the HTML code and the Browser interprets the the HTML code but sends the
scripting code. server side scripting code to the script host/engine
for final execution of the programme
Implementation of JavaScript statements

JavaScript can be implemented using JavaScript statements that are placed within the <script>... </script> in
HTML pages. The script tag is usually placed within the< Head >, however, there is no restriction of its
placement in any part of the page.

The script tag takes two important attributes:


 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"
Both attributes are optional. Any one could be used for implementation purpose.
 Src - a URL to a file that contains the script

Placing the javascript code


There are two ways to place the JavaScript code :
1. Embedded/Inline JavaScript : JavaScript code can be placed either in the HEAD or in the BODY section of a
HTML document. The file is saved as .html. a. It is advised to place JavaScript code in HEAD section when it is
required to be used more than once. If the JavaScript code is small in size and used only once, it is advisable
to put it in the BODY section of the HTML document.
2. External JavaScript : In case, same JavaScript code needs to be used in multiple documents then it is the
best approach to place JavaScript code in external files having extension as . .js.. To do so, we will use src
attribute in <SCRIPT> tag to indicate the link for the source JavaScript file.

Some Key points to remember while writing the code :


 Java Script is case sensitive.
 Statements in JavaScript are generally followed by a semicolon
 JavaScript ignores spaces, tabs, and newlines that appear in the programs
 Any text between a // and the end of a line is treated as a comment - single line comment. Multiline
comment can be inserted by keeping the text within /* */.

Browser portability of Java Script


Java Script is executed by the following browser where it is the default scripting language :
 Netscape Navigator
 Google Chrome
 Mozilla Firefox
However, Internet explorer does not support Java Script but same can be executed by turning on the ActiveX
Controls. For users using IE, that does not support JavaScript or JavaScript is not enabled initially, then the
messages could be displayed using </noscript> immediately after <script>.

Javascrpt Code/Block/Popup Boxes


 Code - It is a sequence of Javascript statements. Each statement is executed by the browser in the
sequence they are written.
 Blocks - It is a group of statements enclosed within { }. The purpose of block is to make the sequence
of statements execute together.
 Popup Boxes - a) Alert b) Confirm c) Prompt
Alert Box - An alert box is often used if you want to make sure information comes through the user.
Prompt - The prompt() method is used to display a dialog with an optional message prompting the
user to input some text. It is often used if the user wants to input a value before entering a page. It
returns a string containing the text entered by the user, or null
Confirm - It is used if we want the user to verify and confirm the information. The user will have to
click either OK or Cancel buttons.
Datatype
A data type, in programming, is a classification that specifies which type of value a variable has and what
type of mathematical, relational or logical operations can be applied to it without causing an error.

Data Types in Java Script


Primitive Datatype Non-primitive Datatype
A primitive data type is a data A non-primitive data type is a
type that is not an object and has data type that is an object and has
no methods methods
1. String 6. Object
2. Number 7. Date
3. Boolean 8. Array
4. Null
5. Undefined
Primitive datatypes have value Non-primitive datatypes have
reference

Variables
A variable is a container which has a name and values are assigned to it. We use variables to hold
information that may change from one moment to the next while a program is running.

Naming Conventions:
 Variable names must begin with a letter or an underscore
 Variable names must not include spaces
 JavaScript is case-sensitive
 Reserved words (i.e., words which indicate an action or operation in JavaScript) cannot be used as
variable names.

Types of variables

Depending on locations where variables have been declared


Local Variable Global Variable
A local variable is a type of variable declared within Global variables are defined outside of a
programming block or functions. It can only be used only function. The global variable will hold its value
inside that code block in which they are declared. The throughout the lifetime of a program. They
local variable exists until the block of the function is in can be accessed within any function defined
under execution. After that, it will be destroyed for the program.
automatically.

Depending upon the number of values they hold


Scalar Variable Global Variable
A local variable is a type of variable declared within Global variables are defined outside of a
programming block or functions. It can only be used only function. The global variable will hold its value
inside that code block in which they are declared. The throughout the lifetime of a program. They
local variable exists until the block of the function is in can be accessed within any function defined
under execution. After that, it will be destroyed for the program.
automatically.
Operators
Operators are a type of command. They perform operations on variables and/or literals and produce a
result.
The Arithmetic Operator - Assume variable A holds 10 and variable B holds 20 then
Operator Description Example
+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiply both operands A * B will give 200
/ Divide numerator by denominator B / A will give 2
% Modulus Operator and remainder of after an integer division B % A will give 0
++ Increment operator, increases integer value by one A++ will give 11
-- Decrement operator, decreases integer value by one A-- will give 9

The Comparison Operators - Assume variable A holds 10 and variable B holds 20 then
Operator Description Example
== Checks if the value of two operands are equal or not, if yes then (A == B) is not
condition becomes true. true.
!= Checks if the value of two operands are equal or not, if values are not (A != B) is true.
equal then condition becomes true.
> Checks if the value of left operand is greater than the value of right (A > B) is not
operand, if yes then condition becomes true. true.
< Checks if the value of left operand is less than the value of right operand, (A < B) is true.
if yes then condition becomes true.
>= Checks if the value of left operand is greater than or equal to the value of (A >= B) is not
right operand, if yes then condition becomes true. true.
<= Checks if the value of left operand is less than or equal to the value of (A <= B) is true.
right operand, if yes then condition becomes true.

The Logical Operators - Assume variable A holds 10 and variable B holds 20 then
Operator Description Example
&& Called Logical AND operator. If both the operands are non zero (A && B) is true.
then then condition becomes true.
|| Called Logical OR Operator. If any of the two operands are non (A || B) is true.
zero then then condition becomes true.
! Called Logical NOT Operator. Use to reverses the logical state of !(A && B) is false.
its operand. If a condition is true then Logical NOT operator will
make false.

The Bitwise Operators - Assume variable A holds 2 and variable B holds 3 then
Operator Description Example
& Called Bitwise AND operator. It performs a Boolean AND (A & B) is 2 .
operation on each bit of its integer arguments.
| Called Bitwise OR Operator. It performs a Boolean OR (A | B) is 3.
operation on each bit of its integer arguments.
^ Called Bitwise XOR Operator. It performs a Boolean exclusive (A ^ B) is 1.
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.
~ Called Bitwise NOT Operator. It is a is a unary operator and (~B) is -4 .
operates by reversing all bits in the operand.
<< Called Bitwise Shift Left Operator. It moves all bits in its first (A << 1) is 4.
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 by 2,
shifting two positions is equivalent to multiplying by 4, etc.
>> Called Bitwise Shift Right with Sign Operator. It moves all bits (A >> 1) is 1.
in its first operand to the right by the number of places
specified in the second operand. The bits filled in on the left
depend on the sign bit of the original operand, in order to
preserve the sign of the result. If the first operand is positive,
the result has zeros placed in the high bits; if the first operand
is negative, the result has ones placed in the high bits. Shifting
a value right one place is equivalent to dividing by 2
(discarding the remainder), shifting right two places is
equivalent to integer division by 4, and so on.
>>> Called Bitwise Shift Right with Zero Operator. This operator is (A >>> 1) is 1.
just like the >> operator, except that the bits shifted in on the
left are always zero,

The Assignment Operators - There are following assignment operators supported by JavaScript language:
Operator Description Example
= Simple assignment operator, Assigns values from right side C = A + B will assign value of A + B
operands to left side operand into C
+= Add AND assignment operator, It adds right operand to the C += A is equivalent to C = C + A
left operand and assign the result to left operand
-= Subtract AND assignment operator, It subtracts right operand C -= A is equivalent to C = C - A
from the left operand and assign the result to left operand
*= Multiply AND assignment operator, It multiplies right operand C *= A is equivalent to C = C * A
with the left operand and assign the result to left operand
/= Divide AND assignment operator, It divides left operand with the C /= A is equivalent to C = C / A
right operand and assign the result to left operand
%= Modulus AND assignment operator, It takes modulus using two C %= A is
operands and assign the result to left operand

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.

The following code shows how to implement typeof operator


<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 => "); Output
document.write(result); Result => B is String
document.write(linebreak); Result => A is Numeric
result = (typeof a == "string" ? "A is String" : "A is Numeric");
document.write("Result => ");
document.write(result);
document.write(linebreak); 48
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Statements
Javascript supports three types of statements :
a) Conditional Statements
b) Looping Statements
c) Sequential Statements

Conditional Statements - Conditional statements are used to decide the flow of execution based on different
conditions. If a condition is true, you can perform one action and if the condition is false, you can perform
another action.

Different Types of Conditional Statements

If statement is used to execute a statement or a block of statements on based of logical expression


(condition). There are mainly three types of conditional statements in JavaScript.
i) If statement
ii) If…Else statement
iii) If…Else If…Else statement Syntax for If..ElseIf..Else Statement
if (condition1)
{
Syntax for If..Else Statement lines of code to be executed if
if (condition) condition1 is true
{ }
Syntax for If Statement Lines of code to be executed if the else if(condition2)
if (condition) condition is true {
{ } lines of code to be executed if
Statement/s else condition2 is true
} { }
lines of code to be executed if the else
condition is false {
} lines of code to be executed if
condition1 is false and condition2 is
false
}

Selection with switch statement - A switch statement is used to execute different statement based on
different conditions. It provides a better alternative than a long series of if. else if . statements.
Syntax -
switch (expression)
{
case label1 : //executes when value
of exp. evaluates to label
statements;
break;
case label2 :
statements;
break;
...
default : statements; //executes when non of the above labels
//matches the result of expression
}
Difference between BREAK and CONTINUE
Break Continue
Break statement is used to exit from the innermost loop, The continue statement skips the statement
switch statement, or from the statement named by label. following it and executes the loop with next
It terminates the current loop and transfers control to iteration. It is used along with an if statement
the statement following the terminated loop inside while, do-while, for, or label
Looping Statements - A loop statement checks to see if some condition is true, and if that condition is true, it
executes a chunk of code. After the code is executed, the condition is checked again. If it is true, the process
starts over again; if it is false, the loop stops and the rest of the code continues along. A loop is a sequence of
instructions that is repeated until a certain condition is reached.

Different Types of loops:


1. Entry Controlled loops: In this type of loops the test condition is tested before entering the loop
body. For Loop and While Loop are entry controlled loops.
2. Exit Controlled Loops: In this type of loops the test condition is tested or evaluated at the end of loop
body. Therefore, the loop body will execute at least once, irrespective of whether the test condition is
true or false. do – while loop is exit controlled loop

while Loop - A while loop is a control flow statement that allows code to be executed repeatedly based on a
given Boolean condition. The while loop can be thought of as a repeating if statement.
 while loop starts with the checking of condition. If it evaluated to true, then the loop body
statements are executed otherwise first statement following the loop is executed. For this reason it
is also called Entry control loop
 Once the condition is evaluated to true, the statements in the loop body are executed. Normally the
statements contain an update value for the variable being processed for the next iteration.
 When the condition becomes false, the loop terminates which marks the end of its life cycle.
Syntax :
while (boolean condition)
{
loop statements...
}
for loop: for loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement
consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy
to debug structure of looping.
It is used for testing the exit condition for a loop. It must return a boolean value. It is also an Entry Control
Loop as the condition is checked prior to the execution of the loop statements.
Syntax :
for (initialization condition; testing condition; increment/decrement)
{
statement(s)
}
do while: do while loop is similar to while loop with only difference that it checks for condition after
executing the statements, and therefore is an example of Exit Control Loop.

 do while loop starts with the execution of the statement(s). There is no checking of any condition for
the first time.
 After the execution of the statements, and update of the variable value, the condition is checked for
true or false value. If it is evaluated to true, next iteration of loop starts.
 When the condition becomes false, the loop terminates which marks the end of its life cycle.
 It is important to note that the do-while loop will execute its statements atleast once before any
condition is checked, and therefore is an example of exit control loop.
Syntax:
do
{
statements..
}
while (condition);
Javascript Functions
Function is a named block of statements which can be executed again and again simply by writing its name
and can return some value. It is useful in making a program modular and understandable.

Function can be defined using the following syntax:


function <function-name>([<parameter list>])
{
. body of the function ..
}
 The function definition begins with keyword function
 It is followed by function's name and optional parameter-list within parenthesis
 Braces are used ( { and } ) to enclose all of the statement in a function.

function Welcome() These statements define a function Welcome that displays


{ an alert message to the user.
alert(“Welcome to NCERT “);
}

Arguements/ Parameters With Function


The arguments received by the function in a list of corresponding values are called parameters. These values
can be assigned to local variables within the function.
name is the arguement/parameter
function Welcome(name)
{
alert(“Welcome to NCERT , “ + name);
}

Calling The Function


a) A function can be called by writing the name of the function along with the list of arguments.

<HTML>
<HEAD>
<TITLE> Defining and calling a Function </title>
<script language=”JavaScript” type=”text/JavaScript”>
function Welcome(name)
Function Definition
{
alert(“Welcome, “ + name);
}
</script>
</HEAD>
<BODY>
<H1> A Function Example</H1>
This example illustrates use of function and popup boxes.
<br>
<script language=”JavaScript”>
var nm = prompt(“What’s your name? “, “Your name please…”);
Welcome(nm);
Calling of function Welcome()
</script>
</BODY>
</HTML>
b) A function call can also be used in an event handler code also. function is defined, it may be used with
events like on Click event. Here, the function simply becomes another JavaScript command.
For example:
<INPUT type = “button”
value = “Calculate”
onClick = calc() >
When the button is clicked, the program automatically calls the calc() function.

Objects In Javascript
It is defined as an unordered collection of related data, of primitive datatype. Objects are a way of organizing
the variables. The different screen elements such as Web pages, forms, text boxes, images, and buttons are
treated as objects.

Javascript supports three types of Objects :


a) String b) Math c) Array

String Object
The JavaScript String Object is one of the most useful of the JavaScript Core Objects. It provides a range of
methods that can be used to perform a variety of string manipulation tasks (replacing parts of a string with
different text, extracting fragments of a string, finding where a particular character appears in a string and
much, much more).
String method and its description
Method Description
charAt() Returns the character at the specified index.
concat() Combines the text of two strings and returns a new string.
indexOf() Returns the index within the calling String object of the first occurrence
of the specified value, or -1 if not found.
lastIndexOf() Returns the index within the calling String object of the last occurrence
of the specified value, or -1 if not found.
match() Used to match a regular expression against a string.
replace() Used to find a match between a regular expression and a string, and to
replace the matched substring with a new substring.
search() Executes the search for a match between a regular expression and a
specified string.
slice() Extracts a section of a string and returns a new string.
split() Splits a String object into an array of strings by separating the string into
substrings.
substr() Returns the characters in a string beginning at the specified location
through the specified number of characters.
toLowerCase() Returns the calling string value converted to lower case.
toUpperCase() Returns the calling string value converted to uppercase.

Property

length Returns the length of the string.


Math Object
The math object provides you properties and methods for mathematical constants and functions. Unlike
other global objects, Math is not a constructor. All the properties and methods of Math are static and can be
called by using Math as an object without creating it.

Math object methods and their description

Method Description

abs() Returns the absolute value of a number.

acos() Returns the arccosine (in radians) of a number.

asin() Returns the arcsine (in radians) of a number.

atan() Returns the arctangent (in radians) of a number.

ceil() Returns the smallest integer greater than or equal to a number.

cos() Returns the cosine of a number.

exp() Returns EN, where N is the argument, and E is Euler's constant,


the base of the natural logarithm.

floor() Returns the largest integer less than or equal to a number.

log() Returns the natural logarithm (base E) of a number.

max() Returns the largest of zero or more numbers.

min() Returns the smallest of zero or more numbers.

pow() Returns base to the exponent power, that is, base exponent.

random() Returns a pseudo-random number between 0 and 1.

round() Returns the value of a number rounded to the nearest integer.

sin() Returns the sine of a number.

sqrt() Returns the square root of a number.

tan() Returns the tangent of a number.

Array Object
An array is an object that can store a collection of items having similar datatype. The items in an array is
accessed by referring to its index number and the index of the first element of an array is zero.

Creation of Array
var students=["John', 'Ann", "Kevin"]; Index of John is 0, Ann is 1 and Kevin is 2

Addition of items into the Array


students[3]="Deon",
students[4]="Emily",
Creation of Array using Array Constructor
var students=new Array("John', 'Ann", "Kevin");
OR
var students=new Array();
students[0]=" John ";
students[1]=" Ann ";
students[2]=" Kevin ";

Array object methods and their description

Method Description

reverse () Reverse the order of items in an array.

sort () Sort the items in an array .

pop () Remove the last item of an array

shift () Remove the first item of an array .

push () Add a value as the last item of the array.

Example :
//Program to create an array.
<html>
<body>
<script language="Javascript">
var i;
Output
var fruits=new Array();
apple
fruits[0]="apple";
banana
fruits[1]="banana";
orange
fruits[2]="orange";
for(i=0;i<fruits.length;i++)
{
document.write(fruits[i]+"<br>");
}
</script>
</body></html>

Example :
//Program to remove the last element from the array by using pop()
<html>
<body>
<p id="demo">Click the button to remove the last array element.</p>
<button onclick="myFunction()">Click me</button>
<script language="Javascript"> Output
var name=["John","Mary","Oliver","Alice"]; Click the button to remove the last
function myFunction() array element
{
name.pop(); Click Me
var x=document.getElementById("demo");
x.innerHTML=name; John Mary Oliver
}
</script>
</body></html>
Example :
//Program to add a new element to the array using push().
<html>
<body>
<p id="demo">Click the button to add a new element to the array.</p>
<button onclick="myFunction()">Click me</button>
<script>
var name=["Alice","Henry","John","Leo"];
function myFunction() Output
{ Click the button to add a new element
name.push("Aayush"); to the array
var x=document.getElementById("demo"); Click Me
x.innerHTML=name;
Alice,Henry,John,Leo, Aayush
}
</script>
</body></html>

//Program to reverse the order of the elements in the array.


<html>
<body>
<p id="demo">Click the button to reverse the order of the element in the array.</p>
<button onclick="myFunction()">Click me</button>
<script>
var alphabet=["z","k","j","h","e"];
function myFunction()
{
alphabet.reverse();
var x=document.getElementById("demo");
x.innerHTML=alphabet;
}
</script>
</body></html>

Compiled by Web Technology Dept,


Apeejay School, Park street

You might also like