0% found this document useful (0 votes)
5 views36 pages

Unit-4 Web Technology

The document provides an overview of JavaScript as a client-side scripting language, detailing its role in creating dynamic web pages and interactive user interfaces. It covers fundamental concepts such as variables, data types, functions, conditional statements, and arrays, along with their syntax and usage. Additionally, it highlights the differences between JavaScript and HTML, as well as the advantages of using JavaScript in web development.
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)
5 views36 pages

Unit-4 Web Technology

The document provides an overview of JavaScript as a client-side scripting language, detailing its role in creating dynamic web pages and interactive user interfaces. It covers fundamental concepts such as variables, data types, functions, conditional statements, and arrays, along with their syntax and usage. Additionally, it highlights the differences between JavaScript and HTML, as well as the advantages of using JavaScript in web development.
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/ 36

Page |1

Unit-4 JavaScript
What is client-side scripting language?
In simple words, client side scripting is a process in which scripts are executed by browsers
without connecting the server.
The code executes on the browser of client’s computer either during the loading of web page or
after the web page has been loaded. Client side scripting is mainly used for dynamic user
interface elements, such as pull-down menus, navigation tools, animation buttons, data
validation purpose, etc. The browser (temporarily) downloads the code in the local computer
and starts processing it without the server. Therefore, the client side scripting is browser
dependent. JavaScript and jQuery are by far the most important client-side scripting languages
or web scripting languages and widely used to create a dynamic and responsive webpage and
websites.

What is JavaScript?
Ans: JavaScript is a text-based programming language that allows us to make web pages
interactive. Where HTML and CSS are languages that give structure and style to web pages,
JavaScript improves the user experience of the web page by converting it from a static page
into an interactive one.
Advantages of JavaScript
• Less server interaction − You can validate user input before sending the page off to the
server. This saves server traffic, which means less load on your server.
• Immediate feedback to the visitors − They don't have to wait for a page reload to see if
they have forgotten to enter something.
• Increased interactivity − You can create interfaces that react when the user hovers
over them with a mouse or activates them via the keyboard.
• Richer interfaces − You can use JavaScript to include such items as drag-and-drop
components and sliders to give a Rich Interface to your site visitors.
Difference between JavaScript and HTML

HTML JAVASCRIPT
HTML is the most basic building block of the JavaScript is a high-level scripting language
Web. It defines the meaning and structure of introduced by Netscape to be run on the
web content. client-side of the web browser.
HTML pages are static which means the It manipulates content to create dynamic
content cannot be changed. web pages

Jhalnath | GM COLLEGE
Page |2

HTML is cross-browser compatible (it works JavaScript is not cross-browser compatible


well with all versions of the browser). (some functions may not work on every
browser).
HTML cannot be embedded inside JavaScript can be embedded inside HTML.
JavaScript.

Lexical Structure
The lexical structure of a programming language is the set of elementary rules that specifies
how you write programs in that language. It is the lowest-level syntax of a language:
Unicode
JavaScript is written in Unicode. This means we can use Emojis as variable names, but more
importantly, you can write identifiers in any language, for example Japanese or Chinese, with
some rules.
Semicolons
Semicolons aren’t mandatory, and JavaScript does not have any problem in code that does not
use them, and lately many developers.
White space
JavaScript does not consider white space meaningful. Spaces and line breaks can be added in
any fashion you might like.
Case sensitive
JavaScript is case sensitive. A variable named something is different from Something. The same
goes for any identifier.
Comments
You can use two kind of comments in JavaScript:
/* */
//
The first can span over multiple lines and needs to be closed and the second comments
everything that’s on its right, on the current line.
Literals and Identifiers
We define literal as a value that is written in the source code, for example a number, a string, a
boolean or also more advanced constructs, like Object Literals or Array Literals.

Jhalnath | GM COLLEGE
Page |3

An identifier is a sequence of characters that can be used to identify a variable, a function, an


object. It can start with a letter, the dollar sign $ or an underscore _, and it can contain digits.
Using Unicode, a letter can be any allowed char, for example an emoji 😄.

Keywords
We can’t use as identifiers any of the following words:
break, do, instanceof, typeof, case, else, new, var, catch, finally, return, void, continue, for,
switch, while, debugger, function, this, with, default, if, throw, delete, in, try, class, enum,
extends, super, const, export, import, implements, let, private, public, interface, package,
protected, static, yield

JavaScript Variables
A variable is simply a name of storage location which stores the data value that can be changed
later on.
The general rules for constructing names for variables are:
• Names can contain letters, digits, underscores, and dollar signs.
• Names must begin with a letter
• Names are case sensitive (y and Y are different variables)
• Reserved words cannot be used as variable names

There are 3 ways to declare a JavaScript variable:


• Using var
• Using let
• Using const

Let var
let is block-scoped. var is function scoped.
let does not allow to redeclare variables. var allows to redeclare variables.

Hoisting does not occur in let. Hoisting occurs in var.

Jhalnath | GM COLLEGE
Page |4

• Using var
The variable declared inside a function with var can be used anywhere within a function. For
example,
// program to print text
// variable a cannot be used here
function greet() {
// variable a can be used here
var a = 'hello';
console.log(a);
}
// variable a cannot be used here
greet(); // hello
Example:
var x=2;
var y=6;
var z=x+y;

• Using let
• Variables defined with let cannot be Redeclared.
Example
let x = "Hello World";
let x = 0;
// SyntaxError: 'x' has already been declared

• Variables defined with let have Block Scope.


Variables declared inside a { } block cannot be accessed from outside the block.

Example
{
let x = 2;
}
// x can NOT be used here

• Using const
• Variables defined with const cannot be Redeclared.
Example
const x = 5;
const x = 0;
// SyntaxError: 'x' has already been declared

• Variables defined with const cannot be Reassigned.

Jhalnath | GM COLLEGE
Page |5

Example
const PI = 3.14159;
PI = 3.14; // This will give an error

• JavaScript const variables must be assigned a value when they are declared:
Example
const g = 9.8; //correct

const g;
g = 9.8; //incorrect

JavaScript Data Types


Most common data types in javascript are numbers, string and objects.
JavaScript has dynamic types. This means that the same variable can be used to hold
different data types:
let x; // Now x is undefined
x = 5; // Now x is a Number
x = "John"; // Now x is a String
x={firstname:”Rohan”,age:25}; // Now x is an object

JavaScript evaluates expressions from left to right. Different sequences can produce
different results:
let x = 5+3+”Ram”;
output: 8Ram
let x = "Ram" + 5 + 3;
output: Ram53
Javascript Expression
An expression is a combination of values, variables, and operators.
Example;
x=5+2;
Here, 5+2 is an expression.

Statements
The programming instructions written in a program in a programming language are
known as statements.
Multiple statements on one line are allowed if they are separated with a semicolon.
a=2;b=3;z=a+b;
Dialog Boxes in Javascript
Dialog boxes are use to provide essential information to the user through pop-up
window.
There are mainly 3 types of dialog box in javascript.

Jhalnath | GM COLLEGE
Page |6

i. alert
ii. confirm
iii. prompt

i. Alert Box
An alert box is often used to “alert” the user for some information message. It
contains a single statement and an OK button. When an alert box pops up, the user
needs to click the OK button to proceed.

ii. Confirm Box


The confirm box is often used if we want the user to “confirm” or accept something.
It contains questions and the OK or CANCEL button to proceed.

iii. Prompt Box


A prompt box can be used to allow the user to input data before entering to a
page. It contains a question, an empty box called “textfield”, and OK and Cancel
button. When prompt box pop ups, the user needs to click either the OK or the
Cancel button to proceed after inputting the data.

Operator in Javascript
Operator is a symbols that can be used to perform mathematical, relational, bitwise,
conditional, or logical manipulations

a. Arithmetic Operator

Operator Use
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement

Jhalnath | GM COLLEGE
Page |7

b. Assignment Operator
There are various Assignment Operators in JavaScript

c. Logical Operators

Operator Use

&& && is known as AND operator. It


returns 1 if they are non-zero;
otherwise, returns 0.
││ || is known as OR operator. It returns
1 if any one of them is non-zero;
otherwise, returns 0.
! ! is known as NOT operator. It reverses
the boolean result of the operand (or
condition). ! false returns true, and
!true returns false.

Jhalnath | GM COLLEGE
Page |8

d. Comparison Operators
Operator Use

== Is equal to
=== Exactly equal to – in value and type
!= Is not equal to
> Is greater than
< Is less than
>= Is greater than or equal to
<= Is less than or equal
to

e. String Operators
Operator Use

+ Concatenation

Function in JavaScript
A JavaScript function is a block of code designed to perform a particular task. A
JavaScript function is executed when "something" invokes it (calls it).
JavaScript Function Syntax
A JavaScript function is defined with the function keyword, followed by a name,
followed by parentheses ().
The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)

function name(parameter1, parameter2, parameter3,…) {


// code to be executed
}

Jhalnath | GM COLLEGE
Page |9

Why we need functions?


we can use the same code many times with different arguments, to produce
different results, this way we can achieve code reusability.
<! DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>This example calls a function to convert from Fahrenheit to Celsius:</p>
<p id="demo"></p>
<script>
function toCelsius(f) {
return (5/9) * (f-32);
}
document.getElementById("demo").innerHTML = toCelsius(77);
</script>
</body>
</html>

Local Variables
Variables declared within a JavaScript function, become LOCAL to the function.

Local variables can only be accessed from within the function.


Example:
// code here can NOT use personName
function myFunction () {
let personName = "Raju";
// code here CAN use personName
}
// code here can NOT use personName

Global JavaScript Variables


A variable declared outside a function, becomes GLOBAL.
Example:
let personName = "Raju";
// code here can use personName
function myFunction () {
// code here can also use personName
}

Jhalnath | GM COLLEGE
P a g e | 10

Conditional Statements in Javascript


Conditional statements are used to perform different actions based on different conditions.
Different Types of Conditional Statements
There are mainly three types of conditional statements in JavaScript.
• If statement
• If…Else statement
• If…Else If…Else statement

• If statement
We can use If statement if we want to check only a specific condition.
Syntax:
if (condition)
{
//lines of code to be executed if condition is true
}

<html>
<head>
<title>IF Statments!!!</title>
<script type="text/javascript">
var age = prompt("Please enter your age");
if(age>=18)
document.write("You are an adult <br />");
if(age<18)
document.write("You are NOT an adult <br />");
</script>
</head>
<body>
</body>
</html>

• If…Else statement
we use If….Else statement when there is a need to test two conditions and execute a
different set of codes.
Syntax:
if (condition)
{

Jhalnath | GM COLLEGE
P a g e | 11

//lines of code to be executed if the condition is true


}
else
{
//lines of code to be executed if the condition is false
}
<html>
<head>
<title>If...Else Statments!!!</title>
<script>
// Get the current hours
var hours = new Date().getHours();
if(hours<12)
document.write("Good Morning!!!<br />");
else
document.write("Good Afternoon!!!<br />");
</script>
</head>
<body>
</body>
</html>

• If…Else If…Else statement


we can use If….Else If….Else statement if you want to check more than two conditions.
Syntax:
if (condition1)
{
//lines of code to be executed if condition1 is true
}
else if(condition2)
{
//lines of code to be executed if condition2 is true
}
else

Jhalnath | GM COLLEGE
P a g e | 12

{
//lines of code to be executed if condition1 is false and condition2 is false
}
<html>
<head>
<script type="text/javascript">
var one = prompt("Enter the first number");
var two = prompt("Enter the second number");
one = parseInt(one);
two = parseInt(two);
if (one == two)
document.write(one + " is equal to " + two + ".");
else if (one<two)
document.write(one + " is less than " + two + ".");
else
document.write(one + " is greater than " + two + ".");
</script>
</head>
<body>
</body>
</html>
\

JavaScript Arrays
In JavaScript, array is a single variable that is used to store different elements. It is often used
when we want to store list of elements and access them by a single variable.

 Array Declaration
var Person = [ ]; // method 1
var Person = new Array(); // method 2

 Initialization of an Array

var Person=[“Ram”,”Hari”,”Gopal”]; //method 1


or
const nums=[];
nums[0]=10;
nums[1]=20;
nums[2]=30;

var Person=new Array(“Ram”,”Hari”,”Gopal”); // method 2

Jhalnath | GM COLLEGE
P a g e | 13

or
var nums=new Array(3); //Creates an array of 3 undefined elements
nums[0]=10;
nums[1]=20;
nums[2]=30;

Example of Array:
<script>
var person=new Array("Ram","Hari","Gopal");
for (i=0;i<person.length;i++){
document.write(person[i] + "<br>");
}
</script>

Repetitive Statements in JavaScript(Loops)

In computer programming, a loop is a sequence of instructions that is repeated until a


certain condition is reached.
JavaScript supports three kinds of looping statements.
a) For Loop
b) While Loop
c) Do While Loop

a)For Loop
For loops are commonly used to count a certain number of iterations to repeat a statement.
Syntax
for ([initialization]; [condition]; [final-expression]) {
// statement
}
Example
<script>
var n1 = prompt("Please enter the number for multiplication table :", "0");
document.write("<h2> Multiplication for your need </h2>");
for( var n2=0;n2<=10;n2++)
{
document.write(n1+" x "+n2+" = "+n1*n2+"<br>");
}
</script>

Jhalnath | GM COLLEGE
P a g e | 14

Regular Expression
In JavaScript, a Regular Expression (RegEx) is an object that describes a sequence of
characters used for defining a search pattern. For example,
/^a...s$/
The above code defines a RegEx pattern. The pattern is: any five letter string starting with a
and ending with s. ( ex: match for alias)

Specify Pattern Using RegEx


To specify regular expressions, metacharacters are used. In the above example (/^a...s$/), ^
and $ are metacharacters.

MetaCharacters
Metacharacters are characters that are interpreted in a special way by a RegEx engine.
Here's a list of metacharacters:

[] . ^ $ * + ? {} () \ |

[] - Square brackets

Square brackets specify a set of characters you wish to match.


for example in expression [abc], if string is 'cat', then there is 2 matches(c and a).
[a-e] is the same as [abcde].

[1-4] is the same as [1234].

We can complement (invert) the character set by using caret ^ symbol at the start of a
square-bracket.

[^abc] means any character except a or b or c.

[^0-9] means any non-digit character.

. - Period
A period matches any single character (except newline '\n').
Expression String Matched?

a No match

.. ac 1 match

acd 1 match

Jhalnath | GM COLLEGE
P a g e | 15

acde 2 matches (contains 4 characters)

^ - Caret
The caret symbol ^ is used to check if a string starts with a certain character.

Expression String Matched?

a 1 match

^a abc 1 match

bac No match

abc 1 match
^ab
acb No match (starts with a but not followed by b)

$ - Dollar
The dollar symbol $ is used to check if a string ends with a certain character.

Expression String Matched?

a 1 match

a$ formula 1 match

cab No match

* - Star
The star symbol * matches zero or more occurrences of the pattern left to it.

Expression String Matched?

ma*n mn 1 match

Jhalnath | GM COLLEGE
P a g e | 16

man 1 match

mann 1 match

main No match (a is not followed by n)

woman 1 match

+ - Plus
The plus symbol + matches one or more occurrences of the pattern left to it.

Expression String Matched?

mn No match (no a character)

man 1 match

ma+n mann 1 match

main No match (a is not followed by n)

woman 1 match

? - Question Mark
The question mark symbol ? matches zero or one occurrence of the pattern left to it.

Expression String Matched?

mn 1 match

man 1 match
ma?n

No match (more than one a


maan
character)

Jhalnath | GM COLLEGE
P a g e | 17

main No match (a is not followed by n)

woman 1 match

{} - Braces
Consider this code: {n,m}. This means at least n, and at most m repetitions of the pattern left
to it.
Expression String Matched?

abc dat No match

abc daat 1 match (at daat)


a{2,3}
aabc daaat 2 matches (at aabc and daaat)

aabc daaaat 2 matches (at aabc and daaaat)

Let's try one more example. This RegEx [0-9]{2, 4} matches at least 2 digits but not more
than 4 digits.
Expression String Matched?

1 match (match at
ab123csde
ab123csde)

[0-9]{2,4}
12 and 345673 3 matches (12, 3456, 73)

1 and 2 No match

| - Alternation

Vertical bar | is used for alternation (or operator).

Expression String Matched?

a|b cde No match

Jhalnath | GM COLLEGE
P a g e | 18

ade 1 match (match at ade)

acdbea 3 matches (at acdbea)

Here, a|b match any string that contains either a or b


() - Group

Parentheses () is used to group sub-patterns. For example, (a|b|c)xz match any string that
matches either a or b or c followed by xz
Expression String Matched?

ab xz No match

(a|b|c)xz abxz 1 match (match at abxz)

axz cabxz 2 matches (at axzbc cabxz)

\ - Backslash

Backslash \ is used to escape various characters including all metacharacters. For example,

\$a match if a string contains $ followed by a. Here, $ is not interpreted by a RegEx engine
in a special way.

If you are unsure if a character has special meaning or not, you can put \ in front of it. This
makes sure the character is not treated in a special way.

Special sequence metacharacters— Meta-characters are characters with a special meaning.


There are many meta character but I am going to cover the most important ones here.

\d — Match any digit character ( same as [0-9] ).


\w — Match any word character. A word character is any letter, digit, and underscore.
(Same as [a-zA-Z0–9_] ) i.e alphanumeric character.
\s — Match a whitespace character (spaces, tabs etc).
\t — Match a tab character only.
\b — Find a match at beginning or ending of a word. Also known as word boundary.
. — (period) Matches any character except for newline.
\D — Match any non digit character (same as [^0–9]).
\W — Match any non word character (Same as [^a-zA-Z0–9_] ).
\S — Match a non whitespace character.

Jhalnath | GM COLLEGE
P a g e | 19

Using regular expressions in JavaScript

Regular expressions are used with the RegExp methods test() and exec() and with
the String methods match(), replace(), search(), and split().

Method Description

exec() Executes a search for a match in a string. It returns an array of information or null on a mismatch.

test() Tests for a match in a string. It returns true or false.

match() Returns an array containing all of the matches, including capturing groups, or null if no match is fou

matchAll() Returns an iterator containing all of the matches, including capturing groups.

search() Tests for a match in a string. It returns the index of the match, or -1 if the search fails.

Executes a search for a match in a string, and replaces the matched substring with a replacement
replace()
substring.

Executes a search for all matches in a string, and replaces the matched substrings with a replaceme
replaceAll()
substring.

split() Uses a regular expression or a fixed string to break a string into an array of substrings.

When you want to know whether a pattern is found in a string, use


the test() or search() methods; for more information (but slower execution) use
the exec() or match() methods.

JavaScript RegExp Modifier

g Modifier

The "g" modifier specifies a global match. A global match finds all matches (compared to only
the first).

Do a global search for "is":


let pattern = /is/g;
let result = text.match(pattern);

Jhalnath | GM COLLEGE
P a g e | 20

i Modifier

The "i" modifier specifies a case-insenitive match.


let text = "Visit W3Schools";
let pattern = /w3schools/i;
let result = text.match(pattern);

m Modifier

The "m" modifier specifies a multiline match. It only affects the behavior of start ^ and end $. ^
specifies a match at the start of a string. $ specifies a match at the end of a string. With the "m"
set, ^ and $ also match at the beginning and end of each line.

let text = ‘Is this

all there

is’

let pattern = /^is/m;

Garbage collection

Memory management in JavaScript is performed automatically and invisibly to us. JavaScript


automatically detects which objects will be needed in later cases and which will be garbage that
is occupying memory without any reason. In JavaScript, when you create a new object, you do
not need any special method to allocate memory for that object. Similarly, when you want to
destroy that object, you do not need to explicitly call any special method to free up the
memory.

Jhalnath | GM COLLEGE
P a g e | 21

Javascript objects

In JavaScript, an object is a standalone entity, with properties and type. Compare it with a cup,
for example. A cup is an object, with properties. A cup has a color, a design, weight, a material
it is made of, etc. The same way, JavaScript objects can have properties, which define their
characteristics.

Object Properties

Properties are the values associated with a JavaScript object. A JavaScript object is a collection
of unordered properties. Properties can usually be changed, added, and deleted, but some are
read only.

Object Constructors

A constructor is a special function that creates and initializes an object instance of a class. In
JavaScript, a constructor gets called when an object is created using the new keyword. The
purpose of a constructor is to create a new object and set values for any existing object
properties.

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Object Constructors</h2>
<p id="demo"></p>
<script>
// Constructor function for Person objects
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
// Create a Person object
const p1 = new Person("Ram", "Rai", 50, "blue");
// Display age
document.getElementById("demo").innerHTML =
"First person is " + p1.age + "years old.";
</script>
</body>
</html>

Prototype and Inheritance

Jhalnath | GM COLLEGE
P a g e | 22

Prototype is used to provide additional property to all the objects created from a constructor
function. we cannot directly add a new property to an existing object constructor, a prototype
can be used to add properties and methods to a constructor function. And objects inherit
properties and methods from a prototype. For example,
The JavaScript prototype property allows you to add new properties to object constructors:
<html>
<body>
<h2>JavaScript Objects</h2>
<p>The prototype property allows you to add new methods to objects constructors:</p>
<p id="demo"></p>
<script>
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
//Person.nationality="English"; we cannot do this
Person.prototype.nationality = "English";//we have to do this
const myFather = new Person("John", "Doe", 50, "blue");
document.getElementById("demo").innerHTML =
"The nationality of my father is " + myFather.nationality;
</script>
</body>
</html>

Object as an associative array


Associative arrays are basically objects in JavaScript where indexes are replaced by user-defined
keys. They do not have a length property like a normal array and cannot be traversed using a
normal for loop. Syntax:
var arr = {key1:'value1', key2:'value2'}
To retrieve all the elements of an associative array we cannot use a simple loop as in the case of
a normal array because elements are not accessible by an index. Here’s how we can do it
instead.

JavaScript Built in Objects

JavaScript has several built-in or core language objects. These built-in objects are available
regardless of window content and operate independently of whatever page your browser has
loaded.

Jhalnath | GM COLLEGE
P a g e | 23

Array Object

Multiple values are stored in a single variable using the Array object.

An Array object can be created by using following ways:

a. Using the Array Constructor:

To create empty array when don’t know the exact number of elements to be inserted in an
array

var arrayname = new Array();

To create an array of given size

var arrayname = new Array(size);

To create an array with given elements

var arrayname = new Array(“element 1”,”element 2”,……..,”element n”);

b. Using the Array Literal Notation:

To create empty array

var arrayname =[ ];

To create an array when elements are given

var arrayname =[“element 1”,”element 2”,……..,”element n”];

Jhalnath | GM COLLEGE
P a g e | 24

Properties of the Array object

Length - Returns the number of elements in the array.

Constructor - Returns the function that created the Array object.

Methods of the Array object

reverse() - Reverses the array elements

concat() - Joins two or more arrays

sort() - Sort the elements of an array

push() - Appends one or more elements at the end of an array

pop() - Removes and returns the last element

shift() - Removes and returns the first element

unshift(), join(), indexOf(), lastIndexOf(), slice(startindex, endindex) are some of the methods
used in Array object.

Date Object

At times when user need to access the current date and time and also past and future date and
times. JavaScript provides support for working with dates and time through the Date object.

Date object can be created as : var today = new Date( );

Dates may be constructed from a year, month, day of the month, hour, minute, and second,
and those six components, as well as the day of the week, may be extracted from a date.

Methods of Date object

Date() - Returns today's date and time

getDate() - Returns the day of the month for the specified date

getDay() - Returns the day of the week for the specified date

getFullYear() - Returns the year of the specified date

Jhalnath | GM COLLEGE
P a g e | 25

getHours() - Returns the hour in the specified date according to local time.

getMilliseconds() - Returns the milliseconds in the specified date according to local time.

getMinute(), getMonth(), getTime(), getTimezoneOffset(), setDate(), setFullYear(), setHours(),


setMilliseconds(), setMinutes(), setMonth(), setSeconds(), setTime() are some of the methods
used in Date object.

Math Object

The Math object is used to perform simple and complex arithmetic operations.

The Math object provides a number of properties and methods to work with Number values

Properties of Math object

PI - The value of Pi

E - The base of natural logarithm e

Methods of Math object

max(a,b) - Returns largest of a and b

min(a,b) - Returns least of a and b

round(a) - Returns nearest integer

ceil(a) - Rounds up. Returns the smallest integer greater than or equal to a

floor(a) - Rounds down. Returns the largest integer smaller than or equal to a

exp(a) - Returns ea

pow(a,b) - Returns ab

abs(a) - Returns absolute value of a

random() - Returns a pseudo random number between 0 and 1

sqrt(a) - Returns square root of a

sin(a) - Returns sin of a (a is in radians)

Jhalnath | GM COLLEGE
P a g e | 26

cos(a) - Returns cos of a (a is in radians)

String Object

in JavaScript, all strings are represented as instances of the String object.

The String object is wrapper class and member of global objects.

String object used to perform operations on the stored text, such as finding the length of the
string, searching for occurrence of certain characters within string, extracting a substring etc.

A String is created by using literals. A string literal is either enclosed within single quotes(‘ ‘) or
double quotes(“ “) var string1= “ Ques10“ ;

Properties of String object

Length - Returns the length of string.

Methods of String object

charAt() - Returns the character at a specified position.

concat() - Combines two or more strings.

toLowerString() - Converts a string to lowercase.

toUpperString() - Converts a string to uppercase.

indexOf(searchtext, index) - Searches for the specified string from the beginning of the string.

lastIndexof(searchtext, index) - Searches for the specified string from the end of the string

Jhalnath | GM COLLEGE
P a g e | 27

DOM
The Document Object Model (DOM) is a programming interface for web documents. It represents
the page so that programs can change the document structure, style, and content. The DOM
represents the document as nodes and objects; that way, programming languages can interact
with the page. When a web page is loaded, the browser creates a Document Object Model of the
page.With the object model, JavaScript gets all the power it needs to create dynamic HTML:

 JavaScript can change all the HTML elements in the page


 JavaScript can change all the HTML attributes in the page
 JavaScript can change all the CSS styles in the page
 JavaScript can remove existing HTML elements and attributes
 JavaScript can add new HTML elements and attributes
 JavaScript can react to all existing HTML events in the page
 JavaScript can create new HTML events in the page

The HTML DOM is a standard for how to get, change, add, or delete HTML elements.

Adding and Deleting Elements

Method Description

document.createElement(element) Create an HTML element

document.removeChild(element) Remove an HTML element

document.appendChild(element) Add an HTML element

document.replaceChild(new, old) Replace an HTML element

document.write(text) Write into the HTML output stream

Example:

<script>
const heading = document.createElement("button");
const headingText = document.createTextNode("Click");
heading.appendChild(headingText);
document.body.appendChild(heading);
};
</script>

Jhalnath | GM COLLEGE
P a g e | 28

Finding HTML Elements

Method Description

document.getElementById(id) Find an element by element id

document.getElementsByTagName(name) Find elements by tag name

document.getElementsByClassName(name) Find elements by class name

Example:

<!DOCTYPE html>

<html>

<body>

<h1>The Document Object</h1>

<h2>The getElementsByClassName() Method</h2>

<p>Change the text of the first element with class="example":</p>

<div class="example">Element1</div>

<div class="example">Element2</div>

<script>

const collection = document.getElementsByClassName("example");

collection[0].innerHTML = "Hello World!";

</script>

</body>

</html>

Jhalnath | GM COLLEGE
P a g e | 29

Changing HTML Elements

Property Description

element.innerHTML = new html content Change the inner HTML of an element


element.attribute = new value Change the attribute value of an HTML
element
element.style.property = new style Change the style of an HTML element

Adding Events Handlers


Method Description
document.getElementById(id).onclick
= function(){code} Adding event handler code to an
onclick event

Common HTML Events

Here is a list of some common HTML events:

Event Description

Onchange => An HTML element has been changed

onclick => The user clicks an HTML element

onmouseover => The user moves the mouse over an HTML element

onmouseout => The user moves the mouse away from an HTML element

onkeydown => The user pushes a keyboard key

onload => The browser has finished loading the page

Jhalnath | GM COLLEGE
P a g e | 30

Introduction to JSON, jQuery, jQuery Integration

JSON

JSON (JavaScript Object Notation) is a text-based, human-readable data interchange format used
to exchange data between web clients and web servers. The format defines a set of structuring
rules for the representation of structured data. JSON is used as an alternative to Extensible Markup
Language (XML).

JSON Syntax Rules

JSON syntax is derived from JavaScript object notation syntax:

 Data is in name/value pairs


 Data is separated by commas
 Curly braces hold objects
 Square brackets hold arrays
The JSON format is almost identical to JavaScript objects. JavaScript has a built in function for
converting JSON strings into JavaScript objects: JSON.parse()

JavaScript also has a built in function for converting an object into a JSON string: JSON.stringify()

The file type for JSON files is ".json"

In JSON, values must be one of the following data types:

 a string
 a number
 an object (JSON object)
 an array
 a boolean
 null

JSON values cannot be one of the following data types:

 a function
 a date
 undefined

Jhalnath | GM COLLEGE
P a g e | 31

JSON.parse()

A common use of JSON is to exchange data to/from a web server. When receiving data from a
web server, the data is always a string.

we need to parse the data with JSON.parse(), and the data becomes a JavaScript object.

we received this text from a web server:

'{"name":"John", "age":30, "city":"New York"}'

Use the JavaScript function JSON.parse() to convert text into a JavaScript object:

const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');

1. <html>
2. <body>
3. <h2>Creating an Object from a JSON String</h2>
4. <p id="demo"></p>
5. <script>
6. const txt = '{"name":"John", "age":30, "city":"New York"}'
7. const obj = JSON.parse(txt);
8. document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;
9. </script>
10. </body>
11. </html>

JSON.stringify()

When sending data to a web server, the data has to be a string. Convert a JavaScript object into a
string with JSON.stringify().

<html>
<body>
<h2>Create a JSON string from a JavaScript object.</h2>
<p id="demo"></p>
<script>
const obj = {name: "John", age: 30, city: "New York"};
const myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;

Jhalnath | GM COLLEGE
P a g e | 32

</script>
</body></html>
JQuery

jQuery is an open-sourced JavaScript library that simplifies creation and navigation of web
applications. Specifically, jQuery simplifies HTML Document Object Model (DOM) manipulation,
Asynchronous JavaScript and XML (Ajax) and event handling. Additionally, jQuery incorporates
JavaScript functionalities by manipulating CSS properties to add effects such as fade-ins and outs
for website elements. jQuery is a widely used JavaScript library and is supported by thousands of
user-created plug-ins.

Features provided by jQuery include:

 A light footprint around 30 kB.


 Supports Chrome, Firefox, Safari, Internet Explorer and Edge.
 Event handling
 Ajax support
 Plug-in support
 DOM element manipulation based on CSS selectors.
 JSON parsing
 Feature detection
 Animation effects

Inserting JQuery

following are the two different ways for adding the jQuery to html page:

1. Download and Include jQuery file

Firstly, we have to download the jquery js file from the following official site of jQuery. Now, we
can include the JQuery file name with location in 'src' attribute of script tag in html file.

2. Include the jQuery by CDN.

You can include jQuery library into your HTML code directly from a Content Delivery Network
(CDN). There are various CDNs which provide a direct link to the latest jQuery library which you
can include in your program.

For ex: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

Jhalnath | GM COLLEGE
P a g e | 33

jQuery Syntax

The jQuery syntax is tailor-made for selecting HTML elements and performing some action on
the element(s).

Basic syntax is: $(selector).action()

 A $ sign to define/access jQuery


 A (selector) to "query (or find)" HTML elements
 A jQuery action() to be performed on the element(s)

Examples:

 $(this).hide() - hides the current element.


 $("p").hide() - hides all <p> elements.
 $(".test").hide() - hides all elements with class="test".
 $("#test").hide() - hides the element with id="test".

Example:

<script>
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
</script>
Important jQuery Functions
If you want to learn how jQuery can benefit you, let’s look at the essential function examples.
1. hide() Function

The hide() function hides HTML elements, making them no longer affect the HTML page. It
serves as an animation method if paired with the duration and easing parameters as well as the
callback function.

2. show() Function

The show() function displays HTML elements. It only works on elements hidden by the hide()
function. Additionally, it becomes an animation method function if given a parameter, just like
hide().

Jhalnath | GM COLLEGE
P a g e | 34

3. fadeIn() Function

The fadeIn() function modifies HTML elements’ opacity to make them appear gradually on the
HTML page. Pair it with the speed or callback function to adjust the animation’s speed and
trigger the next event once the matched elements fully appear.

4.fadeOut() Function

This jQuery function works the opposite of the fadeIn() function. Similar to hide() and show(), the
fadeIn() and fadeOut() become animation methods if given a parameter.

5. fadeToggle() Function

It lets a user display or hide specific elements gradually.

6. slideUp() Function

The slideUp() function hides elements with a sliding animation. Pair it with duration and easing
parameters to adjust the animation’s duration.

7. slideDown() Function

The slideDown() function displays elements with a sliding animation. Similarly, it accepts
duration and easing parameters.

Advantages of jQuery

Easy to learn: jQuery is easy to learn because it supports same JavaScript style coding.

Write less do more: jQuery provides a rich set of features that increase developers' productivity
by writing less and readable code.

Excellent API Documentation: jQuery provides excellent online API documentation.

Cross-browser support: jQuery provides excellent cross-browser support without writing extra
code.

Unobtrusive: jQuery is unobtrusive which allows separation of concerns by separating html and
jQuery code.g parameters.

Jhalnath | GM COLLEGE
P a g e | 35

Cookies in Javascript

Cookies are small strings of data that are stored directly in the browser. A web browser stores
this information at the time of browsing. A cookie contains the information as a string generally
in the form of a name-value pair separated by semi-colons. It maintains the state of a user and
remembers the user's information among all the web pages.

How Cookies Works?

 When a web server has sent a web page to a browser, the connection is shut down, and
the server forgets everything about the user.
 Cookies were invented to solve the problem "how to remember information about the
user":
 When a user visits a web page, his/her name can be stored in a cookie.
 Next time the user visits the page, the cookie "remembers" his/her name.

Usually a cookie is designed to remember and tell a website some useful information about the
user. For example, an online bookstore might use a persistent cookie to record the authors and
titles of books user have ordered. When user return to the online bookstore, browser lets the
bookstore’s site read the cookie. The site might then compile a list of books by the same authors,
or books on related topics, and show that list to the user.

Create a Cookie with JavaScript

document.cookie = "username=John";
You can also add an expiry date (in UTC time).
document.cookie = "username=John; expires=Thu, 18 Dec 2013 12:00:00 UTC";
With a path parameter, you can tell the browser what path the cookie belongs to. By default, the
cookie belongs to the current page.
document.cookie = "username=John; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";

Jhalnath | GM COLLEGE
P a g e | 36

Read a Cookie with JavaScript

let x = document.cookie;

Change a Cookie with JavaScript

we can change a cookie the same way as we create it:

document.cookie = "username=John Smith; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";

Delete a Cookie with JavaScript

set the expires parameter to a past date:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

Complete program to get and set cookie

<!DOCTYPE html>
<html>
<head> <title>Cookie Example</title></head>
<body>
<input type="button" value="setCookie" onclick="setCookie()">
<input type="button" value="getCookie" onclick="getCookie()">
<script>
function setCookie()
{
document.cookie="username=Mohan";
}
function getCookie()
{
if(document.cookie.length!=0)
{
alert(document.cookie);
}
else
{
alert("Cookie not available");
}
}
</script>
</body>
</html>

Jhalnath | GM COLLEGE

You might also like