Unit 3 - Javascript
Unit 3 - 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>
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
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
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.
Logical Operators
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
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
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
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.
1 ?:
Ex : (X>Y)? X : Y
If Condition is true? Then value X : Otherwise value Y
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:
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(expression) {
case value1:
Statements;
break;
case value2:
Statements;
break;
......
default:
Statements;
}
Example:
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.
Example:
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>
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:
Functions
Function Syntax
The syntax of declaring function is given below.
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>
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.
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.
<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>
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:
Or
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:
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:
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()
<script>
var arr1=["C","C++"];
var arr2=["Java","JavaScript"];
var result=arr1.concat(arr2);
document.writeln(result);
</script>
Output :
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 :
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:
The syntax of creating string object using new keyword is given below:
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>
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:
Regular Expressions
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.
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.
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.
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.
o throw statements
o try…catch statements
o try…catch…finally statements.
try…catch
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
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()" >
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.
<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>