Web Tech Module2 & 3 JS
Web Tech Module2 & 3 JS
JavaScript
• JavaScript (js) is a light-weight object-oriented programming language which is used
by several websites for scripting the webpages.
• It was introduced in the year 1995 for adding programs to the webpages in the
Netscape Navigator browser.
<html>
<body>
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
</body>
</html>
JavaScript local variable
A JavaScript local variable is declared inside block or function. It is accessible within
the function or block only.
Example:
<html>
<body>
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
</body>
</html>
JavaScript global variable
A JavaScript global variable is accessible from any function.
A variable i.e. declared outside the function
<html>
<body>
<script>
var data=200;//gloabal variable
function a()
{
document.write(data);
}
a();//calling JavaScript function
</script>
</body>
</html>
JavaScript Data Types
JavaScript provides different data types to hold different types of values.
There are two types of data types in JavaScript.
1. Primitive data type
2. Non-primitive data type
JavaScript is a dynamic type language.
var here to specify the data type. It can hold any type of values such as numbers,
strings etc. For example:
Example:
var a=40;//holding number
var b="Rahul";//holding string
JavaScript primitive data types
There are five types of primitive data types in JavaScript.
Data Type Description
String represents sequence of characters e.g. "hello"
Number represents numeric values e.g. 100
Boolean represents boolean value either false or true
Undefined represents undefined value
Null represents null i.e. no value at all
JavaScript non-primitive data types
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise NOT
<< Bitwise Left Shift
>> Bitwise Right Shift
>>> Bitwise Right Shift with Zero
JavaScript Logical Operators
The following operators are known as JavaScript logical operators.
Operator Description
= Assign
+= Add and assign
-= Subtract and assign
*= Multiply and assign
/= Divide and assign
%= Modulus and assign
JavaScript Special Operators
The following operators are known as JavaScript special operators.
Operator Description
(?:) Conditional Operator returns value based on the condition.
, Comma Operator allows multiple expressions to be evaluated as single statement.
delete Delete Operator deletes a property from the object.
in In Operator checks if object has the given property
new new operator creates an instance (object)
typeof() checks the type of object.
JavaScript If statement
• It evaluates the content only if expression is true
Syntax: if(expression){
//content to be evaluated
}
Example:
<html>
<body>
<script>
var a=20;
if(a>10)
{
document.write("value of a is greater than 10");
}
</script>
</body>
</html>
JavaScript If...else Statement
It evaluates the content whether condition is true of false.
Syntax:
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}
<html>
<body>
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
</body>
</html>
JavaScript If...else if statement
It evaluates the content only if expression is true from several expressions.
Syntax:
if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}
<html>
<body>
<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>
</body>
</html>
JavaScript Switch
The JavaScript switch statement is used to execute one code from multiple expressions.
Syntax:
switch(expression){
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......
default:
code to be executed if above values are not matched;
}
<!DOCTYPE html>
<html>
<body>
<script>
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>
</body>
</html>
JavaScript Loops
The JavaScript loops are used to iterate the piece of code.
It is mostly used in array.
There are four types of loops in JavaScript.
• for loop
• while loop
• do-while loop
• for-in loop
JavaScript For loop
The JavaScript for loop iterates the elements for the fixed number of
times.
It should be used if number of iteration is known.
syntax
for (initialization; condition; increment)
{
code to be executed
}
<!DOCTYPE html>
<html>
<body>
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
</body>
</html>
JavaScript while loop
If the condition evaluates to true, the code inside the while loop is
executed.
This process continues until the condition is false.
syntax
while (condition)
{
code to be executed
}
<!DOCTYPE html>
<html>
<body>
<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>
</body>
</html>
JavaScript do while loop
• The body of the loop is executed at first. Then the condition is
evaluated.
• If the condition evaluates to true, the body of the loop inside the do
statement is executed again.
• This process continues until the condition evaluates to be false.
• do...while loop is similar to the while loop. The only difference is that
in do…while loop, the body of loop is executed at least once even if
the condition evaluates to be false.
The syntax of do while loop is given below.
do{
code to be executed
}while (condition);
<!DOCTYPE html>
<html>
<body>
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
</body>
</html>
JavaScript For In
The JavaScript for in statement loops through the properties of an
Object
Syntax
for (key in object) {
// code block to be executed
}
JavaScript For Of
• The JavaScript for of statement loops through the values of an iterable
object.
• It lets you loop over iterable data structures such as Arrays, Strings, Maps,
NodeLists
Syntax
for (variable of iterable) {
// code block to be executed
}
JavaScript Array
JavaScript array is an object that represents a collection of similar type
of elements.
• By array literal
• By creating instance of Array directly (using new keyword)
• By using an Array constructor (using new keyword)
JavaScript array literal
The syntax of creating array using array literal is given below:
var arrayname=[value1,value2.....valueN];
Example:
<html>
<body>
<script>
var emp=["RAM","SITA"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
</body>
</html>
JavaScript Array directly (new keyword)
The syntax of creating array directly is given below:
var arrayname=new Array();
Here, new keyword is used to create instance of array.
Example:
<html>
<body>
<script>
var i;
var emp = new Array();
emp[0] = "ram";
emp[1] = "sita";
emp[2] = "john";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
</body>
</html>
JavaScript array constructor (new keyword)
Here, you need to create instance of array by passing arguments in constructor so that
we don't have to provide value explicitly.
Example:
<html>
<body>
<script>
var emp=new Array("ram","sita");
for (i=0;i<emp.length;i++)
{
document.write(emp[i] + "<br>");
}
</script>
</body>
</html>
JavaScript Array Methods
Methods Description
concat():
It returns a new array object that contains two or more merged arrays.
find():
It returns the value of the first element in the given array that satisfies the specified condition.
findIndex():
It returns the index value of the first element in the given array that satisfies the specified condition.
slice()
It returns a new array containing the copy of the part of the given array.
sort()
It returns the element of the given array in a sorted order.
pop() It removes and returns the last element of an array.
push() It adds one or more elements to the end of an array.
reverse() It reverses the elements of given array.
shift() It removes and returns the first element of an array.
unshift() It adds one or more elements in the beginning of the given array.
<!DOCTYPE html>
<html>
<body>
<script>
var arr1=["C","C++","Python"];
var arr2=["Java","JavaScript","Android"];
var arr3=["Ruby","Kotlin"];
var result=arr1.concat(arr2,arr3);
document.writeln(result);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script>
var arr=["AngularJS","Node.js","JQuery"];
document.write("Orginal array: "+arr+"<br/>");
document.write("Extracted element: "+arr.pop()+"<br/>");
document.write("Remaining elements: "+ arr);
</script>
</body>
</html>
JavaScript String
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.
syntax
var stringname="string value";
<!DOCTYPE html>
<html>
<body>
<script>
var str="welcome to JavaScript";
document.write(str);
</script>
</body>
</html>
2) By string object (using new keyword)
syntax
var stringname=new String("string literal");
Here, new keyword is used to create instance of string.
<!DOCTYPE html>
<html>
<body>
<script>
var stringname=new String("hello javascript ");
document.write(stringname);
</script>
</body>
</html>
JavaScript String Methods
Methods Description
charAt() It provides the char value present at the specified index.
concat() It provides a combination of two or more strings.
substring() It is used to fetch the part of the given string on the basis
of the specified index.
slice() It is used to fetch the part of the given string. It allows us to
assign positive as well negative index.
toLowerCase() It converts the given string into lowercase letter.
toUpperCase() It converts the given string into uppercase letter.
<!DOCTYPE html>
<html>
<body>
<script>
var str="javascript";
document.write(str.charAt(2));
</script>
</body>
</html>
JavaScript Date Object
The JavaScript date object can be used to get year, month and day. You can display
a timer on the webpage by the help of JavaScript date object
<!DOCTYPE html>
<html>
<body>
<script>
var s=new Date();
document.writeln("Today's day: "+s.getDate());
</script>
</body>
</html>
JavaScript Math
The JavaScript math object provides methods to perform mathematical operation.
Methods Description
abs() It returns the absolute value of the given number.
max() It returns maximum value of the given numbers.
min() It returns minimum value of the given numbers.
pow() It returns value of base to the power of exponent.
random() It returns random number between 0 (inclusive) and 1 (exclusive).
sqrt() It returns the square root of the given number
<!DOCTYPE html>
<html>
<body>
<script>
document.write(Math.pow(2,3));
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script>
document.write(Math.sqrt(16)+ "<br/>");
document.write(Math.sqrt(25));
</script>
</body>
</html>
What is Function in JavaScript
Function is the set of statement enclosed in a specific block
of code to get required functionality to perform specific task
There are two steps to work with function
We create Function:
1. Create a function
• If we want to repeat a code again and again
2. Call that function
• If we want to save our time
Creating a function
• If we want to perform a specific function
function test(){
document.write(“I am Function”);
Syntax
}
function funcName(){
Calling a function (Invocation)
//write code here
test()
}
<html>
<head>
<script>
function test( ){
document.write(“welcome");
document.write(3+3);
}
test();
document.write("<br/>");
function cal( ) {
var a = 32; var b = 12; var c = a + b;
document.write(c)
}
cal()
</script>
</head>
<body>
<h1> functions</h1>
</body>
<html>
<head>
<title>JavaScript Function Problem 1 </title>
<script>
function cal(num1, num2){
document.write("num1 = "+num1)
document.write("num2 = "+num2)
document.write("Addition = "+(num1+num2))
document.write("Substraction = "+(num1-num2))
document.write("Multiplication = "+(num1*num2))
document.write("Division = "+(num1/num2))
document.write("Mod = "+(num1%num2))
}
var a = Number(window.prompt("Enter 1st value"))
var b = Number(window.prompt("Enter 2nd value"))
cal(a,b)
</script>
</head>
<body>
<h1>We are learning js</h1>
</body>
JavaScript RegExp Reference
• A regular expression is a pattern of characters.
• The pattern is used for searching and replacing characters in strings.
• The RegExp Object is a regular expression with added Properties and
Methods.
Syntax
/pattern/modifier(s);
Modifiers
Modifiers are used to perform case-insensitive and global searches:
Modifier Description
g Perform a global match
i Perform case-insensitive matching
m Perform multiline matching
Brackets
Brackets are used to find a range of characters
Expression Description
[abc] Find any character between the brackets
[^abc] Find any character NOT between the brackets
[0-9] Find any character between the brackets (any digit)
[^0-9] Find any character NOT between the brackets (any non-
digit)
(x|y) Find any of the alternatives specified
Metacharacters
Metacharacters are characters with a special meaning:
Metacharacter Description
. Find a single character, except newline or line terminator
\w Find a word character
\W Find a non-word character
\d Find a digit
\D Find a non-digit character
\s Find a whitespace character
\S Find a non-whitespace character
RegExp Object Properties
Property Description
</script>
<p onmouseover="mouseoverevent()"> hi</p>
</body>
</html>
<html>
<head> </head>
<body>
<script >
function clickevent()
{
document.write("sowmya");
}
</script>
<form>
<input type="button" onclick="clickevent()" value="what is ur name?"/>
</form>
</body>
</html>
<html>
<head>Javascript Events</head>
</br>
<body onload="window.alert('Page successfully loaded alert message');">
<script>
document.write("welcome");
</script>
</body>
</html>