0% found this document useful (0 votes)
7 views27 pages

Wid Unit-3 Npre

This document provides an introduction to JavaScript, covering its basics, including variables, data types, and functions, as well as its integration with HTML through the <script> tag. It discusses the advantages and disadvantages of JavaScript, the concept of DHTML, and various types of operators used in JavaScript. Additionally, it explains variable scope, naming rules, and the differences between primitive and non-primitive data types.

Uploaded by

Vishnu Rajeev
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views27 pages

Wid Unit-3 Npre

This document provides an introduction to JavaScript, covering its basics, including variables, data types, and functions, as well as its integration with HTML through the <script> tag. It discusses the advantages and disadvantages of JavaScript, the concept of DHTML, and various types of operators used in JavaScript. Additionally, it explains variable scope, naming rules, and the differences between primitive and non-primitive data types.

Uploaded by

Vishnu Rajeev
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

UNIT-3

Introduction to JavaScript - What is DHTML, JavaScript, basics, variables, string manipulations,


mathematical functions, statements, operators, arrays, functions.
Objects in JavaScript - Data and objects in JavaScript, regular expressions, exception handling.
Q) JavaScript introduction:-
 JavaScript is a dynamic computer programming language.
 It is lightweight and most commonly used as a part of web pages, whose implementations
allow client-side script to interact with the user and make dynamic pages.
 It is an interpreted programming language with object-oriented capabilities.
 JavaScript was first known as Live Script, but Netscape changed its name toJavaScript,
possibly because of the excitement being generated by Java.
 JavaScript can provide functionality, such as password protection, browserdetection, or
display information, such as correct time and date.
 JavaScript is the most popular scripting language on the internet, and works in allmajor
browsers, such as internet explorer, Netscape navigator, etc.
 JavaScript is usually embedded directly in to HTML pages.

Q) Write about basic JavaScript?


How to insert JavaScript into a HTML page:
 You can insert JavaScript into an HTML page by using <script> tag.
 JavaScript is placed between tags starting with <script language=”javascript”> and
ending with </script>.
 The script tag attributes are:
 language: Scripting language name.
 type: Internet content type for a scripting language.
 src: URL for an externally linked script.
 General syntax of JavaScript is as follows:
 <script language=”javascript”>
 JavaScript code here……
 </script>
Q) Different places where JavaScript can be placed in HTML:

 JavaScript is traditionally embedded into a standard html program.


 JavaScript is embedded between <script>……</script> tags. These tags embedded
within the <head>….</head> or <body>…..</body> tags of the HTML program.
 JavaScript placed in the HEAD section of HTML will be executed when called.
 JavaScript placed in the BODY section will be executed only when the page is loaded.
 JavaScript can be placed in various locations in HTML such as
 JavaScript in HEAD section
 JavaScript in BODY section

 JavaScript in both HEAD and BODY

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.

How to display content on browser using JavaScript:


 JavaScript command used for writing output to a page is document.write.
 The document.write command takes the arguments as the required for producingoutput.
 The example below shows how to place JavaScript command inside an HTML page.

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

JavaScript variable Scope:


 The scope of the variable is the region of your program in which it is defined.
JavaScript variable will have only two scopes.
 Global variable: A global variable has global scope which means it is defined
everywhere in your JavaScript code.
 Local variable: A local variable will be visible only within a function where it isdefined.
Function parameters are always local to those functions. Example:<script type = "text/
javascript">

3
varmyVar = "global"; // Declare a global variable
functioncheckscope( ) {
varmyVar = "local"; // Declare a local variable
document.write(myVar); }
</script>Output:
local

JavaScript Variable Naming Rules:


While naming your variables in JavaScript, keep the following rules in mind.
 You should not use any of the JavaScript reserved keywords as a variable name. For example,
break or boolean variable names are not valid.
 JavaScript variable names should not start with a numeral (0-9). They must begin with a letter
or an underscore character. For example, 123test is an invalid variable name but _123test is a
valid one.
 JavaScript variable names are case-sensitive. For example, Name and name are two different
variables.

Q) Explain about Data types in JavaScript?


 JavaScript provides different data types to hold different types of values. JavaScript includes
data types similar to other programming languages like java or c#.
 Data type indicates characteristics of data. It tells the compiler whether the data value is
numeric, alphabetic, data etc.., so that it can perform appropriate operation. There are two
types of data types in JavaScript.
1. Primitive data type 2. Non-primitive (reference) data type
 JavaScript is a dynamic type language, means you don't need to specify type of the variable
because it is dynamically used by JavaScript engine.
 You need to use var here to specify the data type. It can hold any type of values such as
numbers, strings etc.
Example: var a=30; //holding number
var b="balu"; //holding string

I. JavaScript primitive data types:-


There are five types of primitive data types in JavaScript. They are as follows:
 String: - The string data type is used to represents sequence of characters.
Ex: var name=” Hello balu”; orvarstr=new String(“Hello Balu”);
 Number: - The number data type is used to represents numeric values.Ex: var
x=1.2; var y=32;
 Boolean: - The Boolean data type represents boolean value either false or true.Ex: var
x=true; var y=false;
 Undefined: - The undefined data type represents undefined value.Ex: var
person=undefined;
 Null: - The null data type represents null i.e. no value at all.Ex: var

4
person=null;

II. JavaScript non-primitive data types:-


The non-primitive data types are as follows:
 Object: - The object data type represents instance through which we can access
members. Ex: var person={firstname:”Web”, lastname:”technology”};
 Array: - The array data type represents group of similar values.
Ex: var subjects = {“WT”, “DS”, “ICT”,”JAVA”,”CP”};
 RegExp: - The RegExp data type represents regular expressions.Ex: var
reg=new RegExp(“pattern”);

Q) What is DHTML? Differentiate HTML and DHTML.


 DHTML is essentially Dynamic HTML. It is a new way of looking at and controlling thestandard
HTML codes and commands.
 DHTML is a collection of technologies that are used to create interactive andanimated web
sites.
 DHTML gives more control over the HTML elements. It allows one to incorporate a client-side
scripting language, such as JavaScript, a presentation definition language, such as CSS, and the
Document Object Model in HTML web pages.

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.

Q) What is an Operator? Explain types of Operators in JavaScript.


 JavaScript operators are symbols that are used to perform operations on operands.

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:

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 the numerator by the denominator B / A will give 2
% Outputs the remainder of an integer division B % A will give 0
++ Increment operator, increases integer value by A++ will give 11
one
-- Decrement operator, decreases integer value by A-- will give 9
one

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:

Operator Description Example


== Returns true if the two operands are equal (A==B) is not true
!= Returns true if the two operands are not equal (A!=B) is true
> Greater than returns true if the left operand is (A>B) is not true
greater than the right
>= Returns true if the left operand is greater than or (A>=B) is not true
equal to the right one
< Returns true if the left operand is less than the (A<B) is true
right
<= Returns true if the left operand is less than or (A<=B) is true
equal to the right one

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:

Operator Description Example


&& Called logical AND operator. If both the operands (A && B) is true
are non zero then condition becomes true.

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:

Operator Description Example


& Bitwise AND (10==20 & 20==33) = false
| Bitwise OR (10==20 | 20==33) = false
^ Bitwise XOR (10==20 ^ 20==33) = false
~ Bitwise NOT (~10) = -10
<< Bitwise Left Shift (10<<2) = 40
>> Bitwise Right Shift (10>>2) = 2
>>> Bitwise Right Shift with Zero (10>>>2) = 2

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. The + Operator used on Strings:


 The + operator can also be used to add string variable or text values together. Toadd two

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

Q) Explain Conditional statements (Decision making) in JavaScript?


 Conditional statements are used to perform different actions based on different
conditions. In JavaScript we have the following conditional statements.
I. If statement:
 A if statement is used to execute some code if only, if specified conditions is true.
Syntax:
if (condition)
{
Code to be executed if condition is true
}
Example:
<html>
<head>
<title>If Statement</title></head>
<body>
<script type="text/javascript">var
age=20;
if(age>=18)
{
document.write(" You are eligible to vote ");
}
</script></body></html>
Output: You are eligible to vote

II. If-else statement:


 An if..else statement is used to execute some code if the condition is true andanother
code if the condition is false.
Syntax:
if (condition)
{
Code to be executed if condition is true
}
else
{
Code to be executed if condition is false
}
Example:
<html>

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)
{

document.write(" Third division");

}
else
{
document.write(" Fail");
}

</script></body></html>
Output: First Division

IV. Switch statement:


The switch statement is used to select one of several blocks of code to be executed.
Syntax:
Switch (expression)
{
case condition 1: statement(s);
break;

case condition 2: statement(s);


break;
...

case condition n: statement(s);


break;

default: statement(s); break;


}
Example:
<html>

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

Q) Explain Looping statements (Iteration) in JavaScript?


 The JavaScript loops are used to iterate the piece of code using for, while, do whileor for-in
loops. It makes the code compact.
 In JavaScript we have the following looping statements. For and while loops arecalled as
entry level loops and do while loop called as exit level loop.
I. For loop:
 The JavaScript for loop iterates the elements for the fixed number of times. Itshould
be used if number of iteration is known.
Syntax:
for (initialization; condition; increment)
{
code to be executed
}

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

II. while loop:


 The JavaScript while loop iterates the elements for the infinite number of times. Itshould
be used if number of iteration is not known.
Syntax:
while (condition)
{
code to be executed
}

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

III.do while loop:


 The JavaScript do while loop iterates the elements for the infinite number of timeslike while
loop. But, code is executed at least once whether condition is true or false.
Syntax:
do
{
code to be executed
}While(condition);

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

Q) Explain Break and Continue statements in JavaScript

 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

Q) Explain String manipulation (Functions) in JavaScript?


 The String object lets you work with a series of characters and wraps JavaScript’s
string primitive data type with a number of helper methods.
 As JavaScript automatically converts between string primitives and String objects,you can
call any of the helper methods of the String object on a string primitive.
 Use the following syntax to create a String object
varval = new String(string);
The String parameter is a series of characters that has been properly encoded.
String Methods:
1. charAt():charAt() is a method that returns the character from the specified index. Characters
in a string are indexed from left to right. The index of the first character is0, and the index of
the last character in a string, called stringName, is stringName.length –1.
Syntax:string.charAt(index);
Example:varstr=new String(“Welcome to JavaScript”);
document.write("str.charAt(0) is:" + str.charAt(0));
Result: str.charAt(0) is: W

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

5. toLowerCase(): This method returns the given string in lowercase letters.


Syntax:string.toLowerCase();
Example:var str1 = new String("WELCOME TO JAVASCRIPT" );var str2 =
str1.toLowerCase();
document.write("Lowercase String is :" + str2);
Result: Lowercase String is: welcome to javascript

6. toUpperCase():This method returns the given string in Uppercase letters.


Syntax:string.toUpperCase();
Example:var str1 = new String("welcome to javascript" );var str2 =
str1.toUpperCase();
document.write("Uppercase String is :" + str2);
Result: Uppercase String is: 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

3. pow() : This method returns the m to the power of n that is mn.


Syntax: Math.pow(m, n); where m is base and n is exponent number
Example: var m3=Math.pow(8,2);
document.write(“8 to the power of 2 is :”+m3);
Result: 8 to the power of 2 value is: 64

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

6. random() : This method returns the random number between 0 and 1.


Syntax: Math.random(n); where n is a number
Example: var m6=Math.random();
document.write(“The random number is :”+m6);
Result: The random number is: 0.87556841577261

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>

Output: Balu ChiruRaja

Q) Define a Function? Explain about Functions in JavaScript?


 A function is a group of reusable code which can be called anywhere in yourprogram.
 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.
 Every function is made up of a number of statements.

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”);
}

II. Calling a Function:


To invoke (call) a function somewhere later in the script, you would simply need to writethe name
of that function as shown in the following code.
Example:
<html>
<head>
<script type="text/javascript">function
sayHello()
{
document.write ("Hello there!");
}
</script>
</head>
<body>
<form>
<input type="button" onclick="sayHello()" value="Say Hello">
</form>
</body>
</html>

III. Function Parameters:


Till now, we have seen functions without parameters. But there is a facility to pass different
parameters while calling a function. These passed parameters can be captured inside the function
and any manipulation can be done over those parameters. A functioncan take multiple parameters
separated by comma.
Example:
<html>
<body>
<script language=”javascript”>
function
getcube(number){ alert(number*number
*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form></body></html>

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>

Q) Define an Object? Explain how to create Objects in JavaScript?


 A JavaScript object is an entity having state and behaviour (properties and method).For
example: car, pen, bike, chair, glass, keyboard, monitor etc.
 JavaScript is an object-based language. Everything is an object in JavaScript.
 JavaScript is template based not class based. Here, we don't create class to get theobject.
But, we direct create objects.
 Javascript provides a number of application objects such as the document, window,string,
math, array, number and date objects.
 Each object has properties that can be read and sometimes setting JavaScript statements.
Many Objects have methods such as document.write () that give theobject significant
functionality.
Creating Objects: - There are three ways to create objects in JavaScript.
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)

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

2. By creating instance of Object directly (using new keyword): -


 The syntax of creating object directly is given below:var
objectname=new Object();
Here, new keyword is used to create object.
Example:-
<html>
<script language="javascript">
var emp=new Object();
emp.id=101;
emp.name="Priyadarsini";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script> </html>
Result: - 102 Priyadarsini 50000

3. By using an object constructor (using new keyword): -


 Here, you need to create function with arguments. Each argument value can beassigned
in the current object by using this keyword. This keyword refers to thecurrent object.
Example: -
<html>
<script language="javascript"> function
emp(id,name,salary)
{
this.id=id; this.name=name;
this.salary=salary;
}
e=new emp(103,"Priyadarsini",30000);
document.write(e.id+" "+e.name+" "+e.salary);
</script></html>
Result: - 103 Priyadarsini 30000

Explain about Object properties and methods in JavaScript?


 Properties: -
 Properties are the attributes of an object.
 For example the background color and the URL the document was retrieved fromare
attributes of an HTML document.
 An objects properties are accessed by combining the objects name and itsproperty
name as follows:
Objectname.propertyname=”value”;
 In the examples below various properties of the document object are accessedusing the

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

Q) What is Regular Expression? Explain how to create Regular Expressions.


 Regular Expressions are very powerful tools for performing pattern matches.
 You can perform complex tasks that once required lengthy procedures with just afew lines
of code using regular expressions.
 A Regular Expressions is an object that describes a pattern of characters. Regular
Expressions are used to perform pattern-matching and search-and-replace functions on
text.
 Regular Expressions are implemented in two ways:
 Using Literal.
 Using RegExp() constructor.
 The literal syntax looks something like:
var RegularExpression= /pattern/attributes;
 The RegExp() constructor method looks like:
var RegularExpression= new RegExp(“pattern”,”attributes”);
pattern: - A string that specifies the pattern of the regular expression or anotherregular
expression.
attributes : - An optional string containing any of the "g", "i", and "m" attributesthat
specify global, case-insensitive, and multiline matches, respectively.
 RegExp() Object methods: -
Regular expressions are used with the RegExp methods test() and exec() and withthe
String methods match(), replace(), search(), and split().
 test() : A RegExp method that tests for a match in a string. It returns true orfalse.
The test() method syntax is : regexObj.test(str);
 exec() : A RegExp method that executes a search for a match in a string. Itreturns
an array of information or null on a mismatch.
 match() : A String method that executes a search for a match in a string. Itreturns
an array of information or null on a mismatch.
 search() : A String method that tests for a match in a string. It returns theindex of
the match, or -1 if the search fails.
 replace() : A String method that executes a search for a match in a string,and
replaces the matched substring with a replacement substring.
 split() : A String method that uses a regular expression or a fixed string tobreak a
string into an array of substrings.
Example:
<html>
<head>
<title>JavaScript RegularExpressions</title>
</head>
<body>
<script type="text/javascript">
var str = "Javascript is an interesting scripting language";

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

Q) What is Exception? Explain Exception handling in JavaScript.


 Run time error handling is vitally important in all programs. Many object oriented
programming languages provide a mechanism for dealing with general classes of error.
This mechanism is called exception handling.
 An Exception in object based programming is an object, created by dynamically atrun time,
which encapsulates an error and some information about it.
 For instance all incorrect input might be described by UserInputException objects.
 Using Exceptions need two new pieces of the JavaScript language.
The Throw statement: -
 The throw statement allows you to create an exception. If you use this statementtogether
with the try…catch statement, you can control program flow and generate accurate error
message.
Syntax: Throw (Exception);
The try…catch…finally statement: -
 The try statement allows you to define a block of code to be tested for errorswhile it
is being executed.
 The catch statement allows you to define a block of code to be executed, if anerror
occurs in the try block.
 The finally statement lets you execute code, after try and catch, regardless of theresult.
Syntax:
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
finally {

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>

Q)Write about Regular Expression grammar?


 In regular expressions pattern match, the grammar rules are as follows:

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

You might also like