Java Script Notes
Java Script Notes
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
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.
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
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.
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.
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.
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.
<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.
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
Method Description
pow() Returns base to the exponent power, that is, base exponent.
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
Method Description
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>