0% found this document useful (0 votes)
16 views

Unit 3 - Javascript

This is js
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Unit 3 - Javascript

This is js
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

1. Explain Datatypes and variables used in JavaScript.

JavaScript Datatypes

Datatypes are the type of values that can be represented and manipulated in a programming
language.
JavaScript allows you to work with three primitive data types −
 Numbers, eg. 123, 120.50 etc.
 Strings of text e.g. "This text string" etc.
 Boolean e.g. true or false.
JavaScript also defines two trivial data types, null and undefined, each of which defines only a
single value.
In addition to these primitive data types, JavaScript supports a composite data type known
as object.
JavaScript Variable

A JavaScript variable is simply a name of storage location. There are two types of variables in
JavaScript: local variable and global variable.

There are some rules while declaring a JavaScript variable (also known as identifiers).

1. Name must start with a letter (a to z or A to Z), underscore (_), or dollar ($) sign.
2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different variables.

Example

var x = 10;

local variable

A JavaScript local variable is declared inside block or function. It is accessible within the function or
block only. For example:

<script>
function abc(){
var x=10;//local variable
}
</script>
global variable

A JavaScript global variable is accessible from any function. A variable i.e. declared outside the
function or declared with window object is known as global variable. For example:

<script>
var data=200;//gloabal variable
function hello(){
document.writeln(data);
}
hello();//calling JavaScript function
</script>

2.Explain JavaScript operators and its precedence.

JavaScript operators are symbols that are used to perform operations on operands. JavaScript
supports the following types of operators.

 Arithmetic Operators
 Comparison Operators
 Logical (or Relational) Operators
 Assignment Operators
 Conditional (or ternary) Operators

Arithmetic Operators

JavaScript supports the following arithmetic operators −


Assume variable A holds 10 and variable B holds 20, then −

Sr.No. Operator & Description

1 + (Addition)
Adds two operands
Ex: A + B will give 30

2 - (Subtraction)
Subtracts the second operand from the first
Ex: A - B will give -10
3 * (Multiplication)
Multiply both operands
Ex: A * B will give 200

4 / (Division)
Divide the numerator by the denominator
Ex: B / A will give 2

5 % (Modulus)
Outputs the remainder of an integer division
Ex: B % A will give 0

6 ++ (Increment)
Increases an integer value by one
Ex: A++ will give 11

7 -- (Decrement)
Decreases an integer value by one
Ex: A-- will give 9

Comparison Operators

JavaScript supports the following comparison operators −


Assume variable A holds 10 and variable B holds 20, then −

Sr.No. Operator & Description

1 = = (Equal)
Checks if the value of two operands are equal or not, if yes, then the condition becomes
true.
Ex: (A == B) is not true.

2 != (Not Equal)
Checks if the value of two operands are equal or not, if the values are not equal, then the
condition becomes true.
Ex: (A != B) is true.

3 > (Greater than)


Checks if the value of the left operand is greater than the value of the right operand, if
yes, then the condition becomes true.
Ex: (A > B) is not true.

4 < (Less than)


Checks if the value of the left operand is less than the value of the right operand, if yes,
then the condition becomes true.
Ex: (A < B) is true.

5 >= (Greater than or Equal to)


Checks if the value of the left operand is greater than or equal to the value of the right
operand, if yes, then the condition becomes true.
Ex: (A >= B) is not true.

6 <= (Less than or Equal to)


Checks if the value of the left operand is less than or equal to the value of the right
operand, if yes, then the condition becomes true.
Ex: (A <= B) is true.

Logical Operators

JavaScript supports the following logical operators −


Assume variable A holds 10 and variable B holds 20, then −

Sr.No. Operator & Description

1 && (Logical AND)


If both the operands are non-zero, then the condition becomes true.
Ex: (A && B) is true.
2 || (Logical OR)
If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.

3 ! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the Logical NOT
operator will make it false.
Ex: ! (A && B) is false.

Assignment Operators

JavaScript supports the following assignment operators −

Sr.No. Operator & Description

1 = (Simple Assignment )
Assigns values from the right side operand to the left side operand
Ex: C = A + B will assign the value of A + B into C

2 += (Add and Assignment)


It adds the right operand to the left operand and assigns the result to the left operand.
Ex: C += A is equivalent to C = C + A

3 −= (Subtract and Assignment)


It subtracts the right operand from the left operand and assigns the result to the left
operand.
Ex: C -= A is equivalent to C = C - A

4
*= (Multiply and Assignment)
It multiplies the right operand with the left operand and assigns the result to the left
operand.
Ex: C *= A is equivalent to C = C * A

5 /= (Divide and Assignment)


It divides the left operand with the right operand and assigns the result to the left
operand.
Ex: C /= A is equivalent to C = C / A

6 %= (Modules and Assignment)


It takes modulus using two operands and assigns the result to the left operand.
Ex: C %= A is equivalent to C = C % A

Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or false value and then executes
one of the two given statements depending upon the result of the evaluation.

Sr.No. Operator and Description

1 ?:
Ex : (X>Y)? X : Y
If Condition is true? Then value X : Otherwise value Y

3.Explain types of statements used in JavaScript.

Decision making Statements:

There are three forms of if statement in JavaScript.

1. If Statement
2. If else statement
3. if else if statement

If statement

It evaluates the content only if expression is true. The signature of JavaScript if statement is given
below.

if(expression)
{
Statements;
}
Example:

<script type = “text/javascript” >


var a=20;
if(a>10)
{
document.write("value of a is greater than 10");
}
</script>

If...else Statement

It evaluates the content whether condition is true of false. The syntax of JavaScript if-else
statement is given below.

if(expression)
{
Statements;
}
Else
{
Statements;
}

Example:
<script type = “text/javascript”>
var a=20;
if(a%2==0)
{
document.write("a is even number");
}
Else
{
document.write("a is odd number");
}
</script>
If...else if statement

It evaluates the content only if expression is true from several expressions. The signature of
JavaScript if else if statement is given below.

if(expression1)
{
Statements 1;
}
else if(expression2)
{
Statements 2;
}
Else
{
Statements 3;
}

Example:
<script type = “text/javascript”>
var a=20;
var b=30;
var c=10;
if(a>b && a>c){
document.write("a is big");
}
else if(b>c){
document.write("b is big");
}
else{
document.write("c is big");
}
</script>

Switch

Switch is a multiway decision-making statement. The signature of JavaScript switch statement is


given below.

switch(expression) {
case value1:
Statements;
break;
case value2:
Statements;
break;
......

default:
Statements;
}

Example:

<script type = “text/javascript“>


var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document. Write(result);
</script>
Loops

Loop means, block of statements executes repeatedly until condition becomes false . There are
Three types of loops in JavaScript.

1. for loop
2. while loop
3. do-while loop

1) For loop

The for loop iterates the elements for the fixed number of times. It should be used if number of
iterations is known. The syntax of for loop is given below.

for (initialization; condition; increment)


{
Statements;
}

Example:

<script type = “text/ JavaScript”>


for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>

2) while loop

The while loop is an entry control loop. The syntax of while loop is given below.

while (condition)
{
Statements;
}

Example:

<script type=”text/javascript”>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>

3)do while loop

The do while loop Exit control loop. Code is executed at least once whether condition is true or
false. The syntax of do while loop is given below.

do{
Statements;
}while (condition);

Example:

<script type= “text/javascript”>


var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
4.What is function. Explain working with functions in JavaScript.

Functions

A function is a group of reusable code which can be called anywhere in your


program. functions are used to perform operations. We can call JavaScript function many times
to reuse the code.

There are mainly two advantages of JavaScript functions.

1. Code reusability: We can call a function several times so it save coding.


2. Less coding: It makes our program compact. We don’t need to write many lines of code
each time to perform a common task.

Function Syntax
The syntax of declaring function is given below.

function functionName([arg1, arg2, ...argN]){


Statements;
}

Example

Let’s see the simple example of function in JavaScript that does not has arguments.

<script type=”text/javascript”>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>

Function Arguments

We can call function by passing arguments. Let’s see the example of function that has one
argument.

<script type=”text/javascript”>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>

Function with Return Value

We can call function that returns a value and use it in our program. Let’s see the example of
function that returns value.

<script type=”text/javascript”>
function getInfo()
{
return "hello ! How r u?";
}
</script>
<script>
document.write(getInfo());
</script>
5.Explain objects used in JavaScript.

JavaScript Objects

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.

The new operator is used to create an instance of an object. To create an object,


the new operator is followed by the constructor method.

A constructor is a function that creates and initializes an object. JavaScript provides a special
constructor function called Object () to build the object. The return value of the Object
() constructor is assigned to a variable.

Creating Objects in JavaScript

The syntax of creating object directly is given below:

var objectname=new Object();

Here, new keyword is used to create object.

Let’s see the example of creating object directly.

<script type=”text/javascript”>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>

6.Define array. Explain array functions used in JavaScript.

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

Creating Array:

1. The syntax of creating array directly is given below:

var arrayname=new Array();

Here, new keyword is used to create instance of array.

Or

2. We can create array by simply assigning values as shown in below.

Var arrayname = [“val1”,”val2”,”val3”….]

var emp = new Array();


emp[0] = "Arun";
emp[1] = "Varun";
Array Functions:
1. pop()

The pop() method removes the last element from an array:

Example :

<script type=”text/javascript”>
var fruits=["Banana","Orange","mango"];
document.writeln("Orginal array: "+fruits+"<br>");
document.writeln("Extracted element: "+fruits.pop()+"<br>");
</script>

Output:

Orginal array: Banana Orange mango

Extracted element: mango

2. push()

The push() method adds a new element to an array (at the end):

Example
Here, we will add an element in the given array.

<script type=”text/javascript”>
var fruits=["Orange","Banana"];
fruits.push("Apple");
document.writeln(fruits);
</script>
Output:

Orange Banana Apple

3. shift()

The shift() method removes the first array element and "shifts" all other elements to a lower index.

Example:

<script type=”text/javascript”>
var fruits=["Apple",”Banana”,”Orange”];
var result=fruits.shift();
document.writeln(result);
</script>

Output :

Apple

4. unshift()

The unshift() method adds a new element to an array (at the beginning), and "unshifts" older
elements:

Example :

<script type=”text/javascript”>
var Fruits=["Apple",”Banana”,”Orange”];
var result=Fruits.unshift("Mango");
document.writeln(Fruits);
</script>

Output :
Apple Banana Orange Mango

5. concat()

concat() method creates a new array by merging (concatenating) existing arrays:

<script>
var arr1=["C","C++"];
var arr2=["Java","JavaScript"];
var result=arr1.concat(arr2);
document.writeln(result);
</script>

Output :

C c++ Java JavaScript

6. reverse()

The JavaScript array reverse() method changes the sequence of elements of the given array and
returns the reverse sequence.

Example :
<script type=”text/javascript”>
var fruits=["Apple",”Banana”,”Orange”];
var rev=fruits.reverse();
document.writeln(rev);
</script>

Output :

Apple Banana Orange

7.Explain string manipulation in JavaScript .

JavaScript String manipulation:

The JavaScript string is an object that represents a sequence of characters.

There are 2 ways to create string in JavaScript

1. By string literal
2. By string object (using new keyword)

1) By string literal

The string literal is created using double quotes. The syntax of creating string using string literal is
given below:

var stringname="string value";

var str="Hello World";

2) By string object (using new keyword)

The syntax of creating string object using new keyword is given below:

var stringname=new String("string literal");

Here, new keyword is used to create instance of string.

var S =new String("Hello World");

String functions:
1.charAt()

The JavaScript string charAt() method is used to find out a char value present at the specified
index in a string.

<script>
var str="JavaScript";
document.writeln(str.charAt(4));
</script>

2.concat()

The JavaScript string concat() method combines two or more strings and returns a new string.
This method doesn't make any change in the original string.

<script>
var x="JavaScript";
var y=".com";
document.writeln(x.concat(y));
</script>
3.replace()

The JavaScript string replace() method is used to replace a part of a given string with a new
substring.

<script>
var str="Hello World";
document.writeln(str.replace("World","Welcome"));
</script>
4.toUpperCase()

The JavaScript string toUpperCase() method is used to convert the string into uppercase letter.

<script>
var str = "JavaScript";
document.writeln(str.toUpperCase());
</script>
5.toLowerCase()

The JavaScript string toLowerCase() method is used to convert the string into lowercase letter.

<script>
var str = "JAVASCRIPT";
document.writeln(str.toLowerCase());
</script>

6. trim()

The JavaScript String trim() method removes leading and trailing whitespaces from the string.

<script>
var s1=" javascript trim ";
var s2=s1.trim();
document.write(s2);
</script>

8.Explain mathematical functions in JavaScript.

Mathematical functions:

The JavaScript math object provides several constants and methods to perform mathematical
operation. Unlike date object, it doesn't have constructors.

Methods:

abs()

The JavaScript math abs() method returns an absolute value of a given number. The abs() is a
static method of Math.

<script>
document.writeln(Math.abs(-4)+"<br>");
</script>

Output:

exp()

The JavaScript math exp() method returns the exponential form of the given number i.e. e x. Here,
x is the argument and e is the base of natural algorithms.

<script>
document.writeln(Math.exp(1)+"<br>");
</script>

Output:

2.718281828

ceil()

The JavaScript math ceil() method increases the given number up to the closest integer value and
returns it.

<script>
document.writeln(Math.ceil(7.2)+"<br>");
</script>

Output:

floor()
The JavaScript math floor() method decreases the given number up to the closest integer value
and returns it.

<script>
document.writeln(Math.floor(7.2)+"<br>");
</script>

Output:

max()

The JavaScript math max() method compares the given numbers and returns the maximum value.

<script>
document.writeln(Math.max(22,34,12,15)+"<br>");
</script>

Output:

34

min()

The JavaScript math min() method compares the given numbers and returns the minimum value.

<script>
document.writeln(Math.min(22,34,12,15)+"<br>");
</script> :

Output:

12

pow()

The JavaScript math pow() method returns the base to the exponent power such as base exponent.

<script>
document.writeln(Math.pow(2,3)+"<br>");
</script>
Output:

sqrt()

The JavaScript math sqrt() method returns the square root of a number.

<script>
document.writeln(Math.sqrt(16)+ "<br>");
</script>

Output:

9.Explain working with regular expressions in JavaScript with example.

Regular Expressions

A regular expression is an object that describes a pattern of characters.


The JavaScript RegExp class represents regular expressions, and both String and RegExp define
methods that use regular expressions to perform powerful pattern-matching and search-and-
replace functions on text.
Syntax
A regular expression could be defined with the RegExp () constructor, as follows −
var pattern = new RegExp(pattern, attributes);
or simply
Here is the description of the parameters −
 pattern − A string that specifies the pattern of the regular expression or another
regular expression.
 attributes − An optional string containing any of the "g", "i", and "m" attributes that
specify global, case-insensitive, and multi-line matches, respectively.
Sr.No. Modifier & Description

1 I
Perform case-insensitive matching.

2 M
Specifies that if the string has newline

3 G
Performs a global match that is, find all matches rather than stopping after the first
match.

Brackets

Brackets ([]) have a special meaning when used in the context of regular expressions. They are
used to find a range of characters.

Sr.No. Expression & Description

1 [...]
Any one character between the brackets.

2 [^...]
Any one character not between the brackets.

3 [0-9]
It matches any decimal digit from 0 through 9.

4 [a-z]
It matches any character from lowercase a through lowercase z.

5 [A-Z]
It matches any character from uppercase A through uppercase Z.

6 [a-Z]
It matches any character from lowercase a through uppercase Z.

Quantifiers

The frequency or position of bracketed character sequences and single characters can be denoted
by a special character. Each special character has a specific connotation. The +, *, ?, and $ flags
all follow a character sequence.

Sr.No. Expression & Description

1 p+
It matches any string containing one or more p's.

2 p*
It matches any string containing zero or more p's.

3 p?
It matches any string containing at most one p.

4 p{N}
It matches any string containing a sequence of N p's

5 p{2,3}
It matches any string containing a sequence of two or three p's.

6 p{2, }
It matches any string containing a sequence of at least two p's.

7 p$
It matches any string with p at the end of it.

8 ^p
It matches any string with p at the beginning of it.

10.Explain exception handling in JavaScript.

Exception Handling in JavaScript

In programming, exception handling is a process or method used for handling the abnormal
statements in the code and executing them. It also enables to handle the flow control of the
code/program. For handling the code, various handlers are used that process the exception and
execute the code. For example, the Division of a non-zero value with zero will result into infinity
always, and it is an exception. Thus, with the help of exception handling, it can be executed and
handled.

There are following statements that handle if any exception occurs:

o throw statements
o try…catch statements
o try…catch…finally statements.

These exception handling statements are discussed in the next section.

try…catch

A try…catch is a commonly used statement in various programming languages. Basically, it is used


to handle the error-prone part of the code. It initially tests the code for all possible errors it may
contain, then it implements actions to tackle those errors (if occur). A good programming approach
is to keep the complex code within the try…catch statements.

Let's discuss each block of statement individually:

try{} statement: Here, the code which needs possible error testing is kept within the try block.
In case any error occur, it passes to the catch{} block for taking suitable actions and handle the
error. Otherwise, it executes the code written within.

catch{} statement: This block handles the error of the code by executing the set of statements
written within the block. This block contains either the user-defined exception handler or the built-
in handler. This block executes only when any error-prone code needs to be handled in the try
block. Otherwise, the catch block is skipped.

Throw Statement

Throw statements are used for throwing user-defined errors. User can define and throw their own
custom errors. When throw statement is executed, the statements present after it will not execute.
The control will directly pass to the catch block.

Syntax:
throw exception;

finally statement

Finally is an optional block of statements which is executed after the execution of try and catch
statements. Finally block does not hold for the exception to be thrown. Any exception is thrown or
not, finally block code, if present, will definitely execute. It does not care for the output too.

Syntax:
try{
expression;
}
catch(error){
expression;
}
finally{
expression; } //Executable code

11.Explain data validation in JavaScript with example.

JavaScript Form Validation

It is important to validate the form submitted by the user because it can have inappropriate values.
So, validation is must to authenticate user.

JavaScript provides facility to validate the form on the client-side so data processing will be faster
than server-side validation. Most of the web developers prefer JavaScript form validation.

Through JavaScript, we can validate name, password, email, date, mobile numbers and more
fields.

In this example, we are going to validate the name and password. The name can’t be empty and
password can’t be less than 6 characters long.

Here, we are validating the form on form submit. The user will not be forwarded to the next page
until given values are correct.

<html>
<head>
<script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;

if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
</head>
<body>
<form name="myform" method="post" action="abc.jsp" onsubmit="return validateform()" >

Name: <input type="text" name="name"><br/>


Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
</body>
</html>

12.Explain popup boxes /message confirmation boxes used in JavaScript.

JavaScript Message Boxes: alert(), confirm(), prompt()

JavaScript provides built-in global functions to display popup message boxes for different
purposes.

alert()
The alert() function displays a message to the user to display some information to users.
This alert box will have the OK button to close the alert box.
 Syntax:
window.alert([message]);

Example:

<html>
<body>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
alert("I am an alert box!");
}
</script>
</body>
</html>

confirm()
Use the confirm() function to take the user's confirmation before starting some task. For
example, you want to take the user's confirmation before saving, updating or deleting
data.
 Syntax:
bool window.confirm([message]);

Example:
<html>
<body>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var txt =confirm("Press a button!");
if(txt == true) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
}
</script>
</body>
</html>

prompt()

Display a popup box to take the user's input with the OK and Cancel buttons.

string prompt([message], [defaultValue]);

<html>
<body>
<script>
Var a = ParseInt(prompt(“enter a value :”));
Var b = parseInt(prompt(“enter b value :”));
Var c = a+b;
Document.writeln(“result is :” +c);
</body>
</html>

You might also like