Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Web Tech Module2 & 3 JS

JavaScript is a lightweight, object-oriented programming language widely used for web development, enabling dynamic interactivity in HTML documents. It features dynamic typing, object-oriented programming support, and can be run on any platform. Key applications include client-side validation, dynamic menus, and pop-up dialogs, with various methods for integration into HTML.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Web Tech Module2 & 3 JS

JavaScript is a lightweight, object-oriented programming language widely used for web development, enabling dynamic interactivity in HTML documents. It features dynamic typing, object-oriented programming support, and can be run on any platform. Key applications include client-side validation, dynamic menus, and pop-up dialogs, with various methods for integration into HTML.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 81

Module 2

JavaScript
• JavaScript (js) is a light-weight object-oriented programming language which is used
by several websites for scripting the webpages.

• It is an interpreted, full-fledged programming language that enables dynamic


interactivity on websites when applied to an HTML document.

• It was introduced in the year 1995 for adding programs to the webpages in the
Netscape Navigator browser.

• JavaScript is the world's most popular programming language.

• JavaScript is the programming language of the Web.

• JavaScript is easy to learn.


JavaScript Features
• Light Weight Scripting language: it is made for data handling in the browser or the
client side.
• Dynamic Typing: the variable are defined based on the stored value.
• Object-oriented programming support: two important principles with OOP in
JavaScript are:
Object Creation Patterns (Encapsulation)
Code Reuse patterns (Inheritance)
• Platform Independent: write the script once and run it anywhere and anytime.
• Interpreted Language: the script written inside JavaScript is processed line by line.
• Client-side Validations: JavaScript is used for implementing client-side validations.
Application of JavaScript
• JavaScript is used to create interactive websites.
• It is mainly used for:
Client-side validation,
Dynamic drop-down menus,
Displaying date and time,
Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm
dialog box and prompt dialog box)
Different Ways to Use JS in HTML
• Between the head tag of html
• Between the body tag of html
• In .js file (external javaScript)
JavaScript Keywords
* JavaScript statements often start with a keyword to
identify the JavaScript action to be performed.

• JavaScript keywords are reserved words. Reserved words


cannot be used as names for variables.
Keyword Description

var Declares a variable

let Declares a block variable

const Declares a block constant

if Marks a block of statements to be executed on a


condition

switch Marks a block of statements to be executed in different


cases

for Marks a block of statements to be executed in a loop

function Declares a function

return Exits a function

try Implements error handling to a block of statements


• // How to create variables:
var x;
let y;

// How to use variables:


x = 5;
y = 6;
let z = x + y;
<html>
<head>
<script>
document.write("Hello world, in the head section")
</script>
<title>Title for the web page</title>
</head>
<body>
<h1>We are learning JavaScript</h1>
</body>
</html>
<html>
<head>
<title>Title for the web page</title>
</head>
<body>
<script>
document.write("JS in the body section")
</script>
<h1>We are learning JavaScript</h1>
</body>
</html>
<html>
<head>
<script src="file.js" ></script>
<title>Title for the web page</title>
</head>
<body>
<h1>We are learning JavaScript</h1>
</body>
</html>
<html>
<head>
<title>Title for the web page</title>
</head>
<script>
document.write("JS in between head and body section")
</script>
<body>
<h1>We are learning JavaScript</h1>
</body>
</html>
<html>
<head>
<title>web page</title>
</head>
<body>
<h1>We are learning JavaScript</h1>
</body>
</html>
<script>
document.write("JS after the html or end of html doc")
</script>
The JavaScript comments are meaningful way to deliver message. It is used to add
information about the code, suggestions so that end user can easily interpret the
code.
Advantages of JavaScript comments
• To make code easy to understand

Types of JavaScript Comments


1.Single-line Comment
2.Multi-line Comment

JavaScript Single line Comment


It is represented by double forward slashes (//). It can be used before and after the
statement.
JavaScript Multi line Comment
It is represented by forward slash with asterisk then asterisk with
forward slash. For example:

/* your code here */


A JavaScript variable is simply a name of storage location.
There are two types of variables in JavaScript :
1. local variable
2. global variable.
Rules while declaring a JavaScript variable (also known as identifiers).

3. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ )


sign.
4. After first letter we can use digits (0 to 9), for example value1.
5. JavaScript variables are case sensitive, for example x and X are different
variables.
Example:

<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

Data Type Description


Object represents instance through which we can access members
Array represents group of similar values
RegExp represents regular expression
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands.
For example:
var sum=10+20;
Here, + is the arithmetic operator and = is the assignment operator.

There are following types of operators in JavaScript.


1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
JavaScript Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on the operands.
The following operators are known as JavaScript arithmetic operators.
Operator Description Example
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
* Multiplication 10*20 = 200
/ Division 20/10 = 2
% Modulus 20%10 = 0
++ Increment var a=10; a++; Now a = 11
-- Decrement var a=10; a--; Now a = 9
JavaScript Comparison Operators
The JavaScript comparison operator compares the two operands. The
comparison operators are as follows:

Operator Description Example


== Is equal to 10==20 = false
=== Identical (equal and of same type) 10==20 = false
!= Not equal to 10!=20 = true
!== Not Identical 20!==20 = false
> Greater than 20>10 = true
>= Greater than or equal to 20>=10 = true
< Less than 20<10 = false
<= Less than or equal to 20<=10 = false
JavaScript Bitwise Operators
The bitwise operators perform bitwise operations on operands. The
bitwise operators are as follows:

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 Example


&& Logical AND (10==20 && 20==33) false
|| Logical OR (10==20 || 20==33) false
! Logical Not !(10==20) true
JavaScript Assignment Operators
The following operators are known as JavaScript assignment 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.

There are 3 ways to construct array in JavaScript

• 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

global Checks whether the "g" modifier is set


ignoreCase Checks whether the "i" modifier is set
lastIndex Specifies the index at which to start the next match
multiline Checks whether the "m" modifier is set
source Returns the text of the RegExp pattern
RegExp Object Methods
Method Description

exec() Tests for a match in a string. Returns the first match


test() T ests for a match in a string. Returns true or false
toString() Returns the string value of the regular expression
JavaScript Events
• The change in the state of an object is known as an Event.
• When JavaScript code is included in HTML, javascript react over these
events and allow the execution. This process of reacting over the
events is called Event Handling. Thus, JavaScript handles the HTML
events via Event Handlers.
HTML events and their event handlers are:
<html>
<head>
</head>
<body>
<script>
function mouseoverevent()
{
alert("welcome to js");
}

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

You might also like