Wid Unit-3 Npre
Wid Unit-3 Npre
1
JavaScript in External file
The general structure for placing JavaScript in the HEAD section is:
<html><head>
<script language=”javascirpt”>
JavaScript written in HEAD section
</script>
</head>
</body>…</body></html>
The general structure for placing JavaScript in the BODY section is:
<html>
<head>…</head>
<body>
<script language=”javascirpt”>
JavaScript written in BODY section
</script>
</body></html>
Basic Rules:
JavaScript programs contain variables, objects, and functions. They key points thatyou need
to apply in all scripts are listed below:
JavaScript is case sensitive.
JavaScript statements end with semi-colons.
JavaScript has two forms of comments:
Single line comments with a double slash (//) Ex: // this is JavaScript.
Multiline comments begin with “/*” and end with “*/”. Ex: /* multiple lines */
Blocks of code must be surrounded by a pair of curly brackets.
Variables are declared using the var keyword.
Functions have parameters which are passed inside parentheses.
<script language=”javascript”>
document.write(“JavaScript is not java”); // JavaScript statement
</script>
Q) Explain advantages and disadvantages of JavaScript?
2
Advantages of JavaScript:
JavaScript is one of the simple, lightweight, versatile and interpreted programming
languages used to extend functionality in websites.
Executed on the client side: For example, you can validate any user input beforesending a
request to the server. This makes less load on the server.
Relatively an easy language: This is quite easy to learn and the syntax that is close toEnglish.
Instance response to the visitors: Without any server interaction, you don’t have to
wait for a page reload to get your desire result.
Fast to the end user: As the script is executed on the user’s computer, depending on
task, the results are completed almost instantly.
Interactivity increased: Creating interfaces that can react when the user hovers overthem or
activates them using the keyboard.
Rich interfaces: Drag and drop components or slider may give a rich interface to yoursite
visitors.
Disadvantages of JavaScript:
Security issues: Any JavaScript snippets, while appended onto web pages on client
side immediately can also be used for exploiting the user’s system.
Doesn’t have any multiprocessor or multi threading capabilities.
JavaScript cannot be used for any networking applications.
JavaScript does not allow us to read or write files.
JavaScript render varies: JavaScript may be rendered by different layout engines differently.
As a result, this causes inconsistency in terms of interface and functionality.
Q) Explain Variables in JavaScript?
Like many other programming languages, JavaScript has variables. Variables can bethought
of as named containers.
You can place data into these containers and then refer to the data simply by namingthe
container.
Before you use a variable in a JavaScript program, you must declare it. Variables aredeclared
with the var keyword. Ex: var money;
You can also declare multiple variables with the same var keyword.Ex: var
age, ID;
Variables declaration and assignment can be done in a single step.Ex: var
age=34;
3
varmyVar = "global"; // Declare a global variable
functioncheckscope( ) {
varmyVar = "local"; // Declare a local variable
document.write(myVar); }
</script>Output:
local
4
person=null;
HTML DHTML
DHTML stands for Dynamic Hypertext
1.HTML stands for Hypertext markup markup language
language
2. HTML is a mark-up language DHTML is a collection of technology.
( HTML, CSS, javascript and DOM).
3. HTML creates static web pages. DHTML creates dynamic web pages,
4. HTML creates a plain page without any DHTML creates a page with HTML, CSS, DOM
styles and Scripts called as HTML and Scripts called as DHTML.
5. HTML sites will be slow upon client-side DHTML sites will be fast enough upon client-
technologies side technologies.
6. HTML cannot have any server side code DHTML may contain server side code.
7. In HTML, there is no need for database DHTML may require connecting to a
connectivity. database as it interacts with user.
8. HTML files are stored with .htm or .html DHTML files are stored with .dhtm
extension extension.
9.HTML does not require any processing DHTML requires processing from browser
from browser, which changes its look and feel.
5
For example: var sum= a + b;
Where ‘+’ is the arithmetic operator and ‘=’ is the assignment operator and a, b are
operands. The following are types of operators in JavaScript.
1. Arithmetic Operators:
Arithmetic operators are used to perform arithmetic operations on the operandsand
return a single value. The following operators are known as JavaScript arithmetic
operators. Assume variable A holds 10 and variable B holds 20 then:
2. Comparison Operators:
A comparison operator compares its operands and return a logical value based onwhether
the comparison is true or not. The comparison operators are listed belowassume variable A
holds 10 and variable B holds 20 then:
3. Logical Operators:
These operators are typically used with Boolean (logical) values. They return a Boolean
value. The Boolean operators are listed below, Assume variable A holds 10and variable B
holds 20 Then:
6
|| Called Logical OR operator. If any of the two (A || B) is true
operands are non zero then condition becomes
true
! Called Logical NOT operator. Logical NOT returns !( A && B) is false
false if the operand evaluates to true. Otherwise it
returns true
4. Assignment Operators:
These assignment operators (=) to assign a value to a variable or constant or
expression assigned for given variable. The assignment operators listed below
Operator Description Example
= Assign the value of the right operand to the left C = A + B will assign
operand value of A + B into C
+= Adds together the operands and assigns the result C += A is equivalent to
to the left operand C=C+A
-= It subtracts right operand from the left operand C -= A is equivalent to C
and assigns the result to left operand. =C–A
*= It multiplies right operand with the left operand C *= A is equivalent to C
and assigns the result to left operand. =C*A
/= It divides left operand with the right operand and C /= A is equivalent to C
assigns the result to left operand. =C/A
%= It takes modulus using two operands and assigns C %= A is equivalent to C
the result to left operand. =C%A
5. Bitwise Operators:
The bitwise operators perform bitwise operations on operands. The bitwise
operators are as follows:
6. Conditional Operator (? :)
JavaScript provides conditional operator which is used for comparing two expressions, also
contains a conditional operator that assigns a value to a variableused on some condition.
Syntax: variable = (condition)? value1:value2; Example:
result = (marks>=35)? “Passed”: “Failed”;
Displays result depends on marks, if marks greater than are equal to 35 displays aspassed
otherwise failed message.
7
or more string variables together, use + operator.
text1=” Hello”; text2= “Welcome to Javascript”; text3=text1+text2;
After executions of the statements are above, the variable text3 contains “Hello
Welcome to JavaScript”.
8
<head><title>If else Statement</title></head>
<body>
<script type="text/javascript">var
age=20;
if(age>=18)
{
document.write(" You are eligible to vote ");
}
else {
document.write(" You are not eligible to vote ");
}
</script></body></html>
Output: You are eligible to vote
III. If-else-if statement (else if ladder):
An if-else-if statement is used to select one of several blocks of code to be executed.
Syntax:
if (condition1)
{
Code to be executed if condition1 is true
}
else if (condition2)
{
Code to be executed if condition2 is true
}
else if (conditionN)
{
Code to be executed if conditionN is true
}
else
{
Code to be executed if condition1 and 2 are not true
}
Example:
<html>
<head><title>If else if Statement</title></head>
<body>
<script type="text/javascript">var
marks=65;
if(marks>=75)
{
document.write(" Distinction");
9
}
else if (marks>=60 && marks<75)
{
document.write(" First division");
}
else if (marks>=50 && marks<60)
{
document.write(" Second division");
}
else if (marks>=40 && marks<50)
{
}
else
{
document.write(" Fail");
}
</script></body></html>
Output: First Division
10
<head><title>If Statement</title></head>
<body>
<script type="text/javascript">var
grade=A;
switch (grade)
{
case ‘O’: document.write(" Out Standing”);
break;
case ‘A’: document.write(" Excellent”);
break;
case ‘B’: document.write(" Good”);
break;
case ‘C’: document.write(" Very Good”);
break;
case ‘D’: document.write(" Fair”);
break;
default: document.write(" Fail”);
break;
</script></body></html>
Output: Excellent
Example:
<html>
<head><title>For Loop Statement</title></head>
<body>
<script type=”text/javascript”>
for (var i=1; i<=5; i++)
11
{
document.write(i + "<br/>") ;
}
</script></body></html>
Output: 1 2 3 4 5
Example:
<html>
<head><title>While Loop Statement</title></head>
<body>
<script type=”text/javascript”>
var i=0; while (i<=5)
{
document.write(i + "<br/>")
}
</script></body></html>
Output: 1 2 3 4 5
Example:
<html>
<head><title>do while Loop Statement</title></head>
<body>
<script type=”text/javascript”>
12
var i=0;do
{
document.write(i + "<br/>")
}
while (i<=5);
</script></body></html>
Output: 1 2 3 4 5
JavaScript provides full control to handle loops and switch statements. There maybe 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 andstart 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 thenext
iteration of any loop respectively.
break and continue statements are used in for, while and do while loops.
I.ThebreakStatement:
The break statement, which was briefly introduced with the switch statement, isused to
exit a loop early, breaking out of the enclosing curly braces.
Syntax: break;
Example:
<html>
<head><title>Break statement</title></head>
<body>
<script type="text/javascript">var i;
for(i=0;i<=5;i++)
{
if(i==4)
{
break;
}
document.write(i+"<br>");
}
</script></body></html>
Output: 0 1 2 3
II. ThecontinueStatement:
13
The continue statement breaks one iteration (in the loop), if a specified conditionoccurs,
and continues with the next iteration in the loop.
Syntax: continue;
Example:
<html>
<head><title>Continue statement</title></head>
<body>
<script type="text/javascript">var i;
for(i=0;i<=5;i++)
{
if(i==4)
{
continue;
}
document.write(i+"<br>");
}
</script></body></html>
Output: 0 1 2 3 5
2. charCodeAt(): This method returns a number indicating the Unicode value of the
character at the given index. charCodeAt() always returns a value that is less than 65,536.
Syntax:string.charCodeAt(index);
Example:varstr=new String(“Welcome to JavaScript”);
document.write("str.charCodeAt(0) is:" + str.charCodeAt(0));
14
Result: str.charCodeAt(0) is:87
3. indexOf(): This method returns the index position of the given string.
Syntax:string.indexOf(string);
Example:var str1 = new String( "Welcome to JavaScript" );var index
= str1.indexOf( "JavaScript" );
document.write("indexOf found String is :" + index );
Result: indexOf found String is:11
4. concat():This method adds two or more strings and returns a new single string.
Syntax:string.concat(string2, string3, ..., stringN]);
Example:var str1 = new String( "Hello" ); var str2 =
new String(" Welcome to JavaScript" );var str3 =
str1.concat( str2 );
document.write("Concatenated String is :" + str3);
Result: Concatenated String is:Hello Welcome to JavaScript
7. slice():The slice(beginIndex, endIndex) method returns the parts of string from given
beginIndex to endIndex. In slice() method, beginIndex is inclusive and endIndex is exclusive.
Syntax:string.slice(begindex, endindex);
Example:var str1 = new String("welcome to JavaScript" );var str2 =
str1.slice(3,6);
document.write("sliced value is :" + str2);
Result: sliced value is: come
8. split() :This method splits a String object into an array of strings by separating thestring
into substrings.
Syntax:string.split(separator,limit);
15
Example:var str1 = new String("welcome to JavaScript let you start" );
var str2 = str1.split(“ “,6);
document.write("splitted value is :" + str2);
Result: splitted value is: welcome, to, JavaScript, let, you, start
9. trim():The JavaScript String trim() method removes leading and trailing whitespacesfrom the
string.
Syntax:string.trim();
Example:var str1 = new String(" welcome to JavaScript " );var str2
= str1.trim();
document.write("Trimmed string is :" + str2);
Result: Trimmed string is: welcome to JavaScript
10. substr():This method returns the characters in a string beginning at the specifiedlocation
through the specified number of characters.
Syntax:string.substr(start, length);
Example:var str1 = new String("welcome to JavaScript ");var str2 =
str1.substr(3,6);
document.write("The sub string is :" + str2);
Result: The sub string is: come
Q)Explain Mathematical Functions in JavaScript?
The Math object provides you properties and methods for mathematical constantsand
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 asan object
without creating it.
Mathematical functions and values are part of a built in javaScript object calledMath.
You refer to the constant pi as Math.PI and you call the sine function as Math.sin(x),where x
is the method's argument.
The syntax to call the properties and methods of Math are as follows
varpi_val = Math.PI; varsine_val =
Math.sin(30);
Math Methods:
1. abs() : This method returns the absolute value for the given number.
Syntax: Math.abs(n); where n is a number
Example: var m1=Math.abs(-21);
document.write(“ The absolute value of -21 is :”+m1);
Result: The absolute value of -21 is: 21
2. sqrt() : This method returns the square root of the given number.
Syntax: Math.sqrt(n); where n is a number
Example: var m2=Math.sqrt(16);
16
document.write(“ The square root of 16 is :”+m2);
Result: The square root of 16 is: 4
4. ceil() :This method returns the largest integer for the given number.
Syntax: Math.ceil(n); where n is a number
Example: var m4=Math.ceil(45.89);
document.write(“a ceil value of 45.89 is :”+m4);
Result: aceil value of 45.89 is: 46
5. floor() : This method returns the smallest integer for the given number.
Syntax: Math.floor(n); where n is a number
Example: var m5=Math.floor(45.89);
document.write(“a floor value of 45.89 is :”+m5);
Result: afloor value of 45.89 is: 45
7. max() : This method returns the largest of zero or more numbers. If no argumentsare
given, the results is –Infinity.
Syntax: Math.max(valu1,valu2,………,valun); where n is a number
Example: var m7=Math.max(50,30,60,90);
document.write(“The maximum value is :”+m7);Result: The
maximum value is: 90
8. min() : This method returns the smallest of zero or more numbers. If no argumentsare
given, the results is –Infinity.
Syntax: Math.max(valu1,valu2,………,valun); where n is a number
Example: var m8=Math.max(50,30,60,90);
document.write(“The maximum value is :”+m8);
Result: The maximum value is: 30
9. sin() :This method returns the sine of a number. The sin method returns a numericvalue
17
between -1 and 1, which represents the sine of the argument.
Syntax: Math.sin(n); where n is a number
Example: var m9=Math.sin(90);
document.write(“The sine value of 90 is :”+m9);
Result: The sine value of 90 is: 0.8939966636005578
10. tan() :This method returns the tangent of a number. The tan method returns anumeric
value that represents the tangent of the angle.
Syntax: Math.tan(n); where n is a number
Example: var m11=Math.tan(45);
document.write(“The tangent value of 45 is :”+m11);
Result: The tangent value of 45 is: 1
11. log() :This method returns the natural logarithm (base E) of a number. If the value ofnumber
is negative, the return value is always NaN.
Syntax: Math.log(n); where n is a number
Example: var m12=Math.log(10);
document.write(“The logarithm value of 10 is :”+m12);
Result: The logarithm value of a 10 is: 2.302585092994046
Q) Explain about Arrays in JavaScript?
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 ofan array
as a collection of variables of the same type.
There are 3 ways to construct array in JavaScript
By array literal:
The syntax of creating array using array literal is given below:
Syntax: var arrayname=[value1,value2.....valueN];
As you can see, values are contained inside [ ] and separated by, (comma).
Example:
<html>
<script>
var emp=["Balu","Chiru","Raja"];for
(i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
</html>
Output: Balu ChiruRaja
By creating instance of Array directly (using new keyword)
The syntax of creating array directly is given below:
Syntax: var array_name=new Array();
18
Here, new keyword is used to create instance of array.
Example:
<html>
<script>
var i;
var emp = new Array();emp[0] =
"Balu";
emp[1] = "Chiru";
emp[2] = "Raja";
for
(i=0;i<emp.length;i++){ document.write(e
mp[i] + "<br>");
}
</script></html>
Output: Balu ChiruRaja
By creating array constructor (new keyword)
Here, you need to create instance of array by passing arguments in constructor so that wedon't
have to provide value explicitly.
Syntax: var emp=new Array("Balu","Chiru","Raja");
Example:
The example of creating object by array constructor is given below.
<html>
<script>
var emp=new Array("Balu","Chiru","Balu");for
(i=0;i<emp.length;i++){ document.write(emp[i] +
"<br>");
}
</script></html>
I. 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:
19
function function_Name(parameters list)
{
//code to be executed
}
Example:
function sayHallo()
{
Alert(“Hello there”);
}
20
IV. Function Return Values:
The return keyword is used to return values from function. Function can returnresults.
Results are returned using the return statement.
Example:
<html>
<body>
<script language=”javascript”>
function getInfo(){
return "hello welcome to Javascript” ;
}
<script>
document.write(getInfo());
</script>
</body>
</html>
1. By object literal:-
The syntax of creating object using object literal is given below: object
={property1:value1,property2:value2 ............... propertyN:valueN}
As you can see, property and value is separated by : (colon).
Example: -
<html>
<script language="javascript">
emp={ id:102,name:"Subbu",salary:40000 }
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
</html>
21
Result: - 102 Subbu 40000
22
dot operator and assigned to a variable called result.
Getting the properties of an Object:
Result=document.location;
(result will contain the URL of the document).
Result=document.bgcolor;
(result will contain the background color of the document)
Setting the properties of an Object: It is also possible to assign values to some object
properties. So while it doesn’t make sense to be able to change the location where the
document came from, you can change the background colorof the document this way:
document.bgcolor=”#800080”;
document.bgcolor=”Orange”;
Methods: -
Methods are a way of asking an object to do something more complicated thanchanging
a property.
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.
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(“JavaScript Expression”);
Here write() is a method (a function) that belongs to the document object. Callingwrite() is
like asking a document to append HTML to itself. The javascript expression inside the
round brackets will be evaluated and the result (whatever itis) written out to the HTML
page.
Here are some more methods for the document object:close(),
open(), writeln(), getElementById(“ID”)
Example: -
<script type="text/javascript">
var book = new Object(); // Create the object
book.subject = "Web Technology"; // Assign properties to the object
book.author = "Balu";
</script></head>
<body>
<script type="text/javascript">
document.write("Book name is : " + book.subject + "<br>"); // Using write() Method
document.write("Book author is : " + book.author + "<br>"); // Using write() Method
</script></body>
Result: -
Book name is : Web TechnologyBook
23
name is : Balu
24
var rem = new RegExp( "script", "g" );var result =
rem.exec(str);
document.write("Test 1 - returned value is : " + result);rem = new
RegExp( "pushing", "g" );
var result = rem.exec(str);
document.write("<br />Test 2 - returned value is : " + result);
</script>
</body>
</html>
Result:
Test 1 - returned value is : script
Test 2 - returned value is : null
25
Block of code to be executed regardless of the try / catch result
}
Example:
<html>
<head>
<script type="text/javascript">function
myFunc()
{
var a = 100;var b = 0;
try{
if ( b == 0 )
{
throw( "Divide by zero error." );
}
else
{
var c = a / b;
}
}
catch ( e )
{
alert("Error: " + e );
}
}
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>
Token Description
^ Match at the start of the input string
26
$ Match at the end of the input string
* Match 0 or more items
+ Match 1 or more items
? Match 0 or 1 time
a/b Match a or b
{n} Match the string n times
\d Match a digit
\D Match anything except for digits
\w Match anything alphanumeric characters or the underscore.
\W Match anything except alphanumeric characters or the underscore.
\s Match a whitespace character.
\S Match anything except for whitespace characters.
\t Matches horizontal characters.
[xyz] Match any one character enclosed in the character set ex: /[0-9]/
() Grouping characters together to create a clause.
27