0% found this document useful (0 votes)
58 views44 pages

Unit-2 FSD

The document provides an overview of JavaScript, covering its basics, syntax, variable declaration, operators, and comments. It explains the advantages of using JavaScript for web development, including interactivity and reduced server load. Additionally, it includes examples of JavaScript code placement in HTML and demonstrates various operators and their usage.

Uploaded by

hazira0534
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)
58 views44 pages

Unit-2 FSD

The document provides an overview of JavaScript, covering its basics, syntax, variable declaration, operators, and comments. It explains the advantages of using JavaScript for web development, including interactivity and reduced server load. Additionally, it includes examples of JavaScript code placement in HTML and demonstrates various operators and their usage.

Uploaded by

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

ADITYA COLLEGE OF ENGINEERING, MADANAPALLE

Full Stack Development


(20A05703A)

Unit – II
Front end Development

Regulation – R20
Unit – III
Frontend Development

Javascript basics - OOPS Aspects of JavaScript - Memory usage and


Functions in JS - AJAX for data exchange with server - jQuery Framework
jQuery events - UI components - etc. JSON data format.

2.1 JavaScript Basics:-

What is JavaScript?
 JavaScript was initially created to “make web pages alive”.
 The programs in this language are called scripts. They can be written right in a web
page‟s HTML and run automatically as the page loads.
 Scripts are provided and executed as plain text. They don‟t need special preparation
or compilation to run.
 JavaScript is a client and server-side object-based scripting language that is used to
make interactive Web pages. A scripting language is a lightweight programming
language with less complexity.
 JavaScript is the most usually used scripting language to add dynamic and
interactivity to Web pages. This is because JavaScript, written on the client-side,
executes on a client browser, thereby reducing the load on the server.

JavaScript is an Interpreted Language


JavaScript is an interpreted language, which implies that scripts written to JavaScript are
processed line by line. These scripts are interpreted by the JavaScript interpreter, which is
a built-in component of the Web browser.

JavaScript can be written on the client-side as well server-side. Client-side JavaScript


allows you to validate only those programs that execute and produce the result on the
client-machine. In contrast, server-side JavaScript validates only those programs that
execute on the server. JavaScript includes various built-in objects and features that can be
used to make your HTML pages dynamic.

JavaScript is platform-independent
JavaScript is platform-independent, which implies that you need to write the script once
and can run it on any platform or browser without affecting the output of the script.

Why to Learn JavaScript ?


There are the three languages, all web developers must know, these are the following:
 HTML - to define the content of web pages
 CSS - to define the layout of web pages
 JavaScript - to program the behaviour of web pages

Advantages of JavaScript
Here are the advantages of JavaScript:
 Less server interaction
 More interactivity
 Richer interfaces
 Fast feedback to visitors

Here is a simple JavaScript example.

<html>
<head></head>
<body>
<p>Before the script...</p>
<script>
alert( 'Hello, world!' );
Or
document.write(“Hello World”);
</script>
<p>...After the script.</p>
</body>
</html>

JavaScript Syntax
 It is a set of rules that defines how JavaScript programs are constructed.
 A JavaScript program consists of JavaScript statements that is placed inside
the HTML

<script> ... </script> tag in a web page.

 You are free to place the <script> containing your JavaScript program anywhere
within your web page, but to keep it within the <head> tag is the preferred way.
Here is the general form shows how script tag plays a role in placing JavaScript
code inside it:
<script ...>
JavaScript code
</script>

The script tag takes two important attributes:


 language - The language attribute is used to specify what scripting language you are
using
 type - The type attribute is what is now recommended to indicate the scripting
language in use and its value should be set to "text/javascript"

Now the general form or syntax of your JavaScript code segment will be:
<script language="javascript" type="text/javascript">
JavaScript code
</script>
JavaScript Syntax Example
Here is an example demonstrates syntax of a simple JavaScript example:
<html>
<body>
<script language="javascript" type="text/javascript">
document.write("Hello JavaScript!")
</script>
</body>
</html>

Here is another JavaScript program, also demonstrates the JavaScript syntax:


<!DOCTYPE html>
<html>
<head>
<title>JavaScript Syntax</title>
</head>
<body>
<p id="syntax_para1"></p>
<script>
var num1 = 10;
var num2 = 20;
var res = num1 + num2;
document.getElementById("syntax_para1").innerHTML = res;
</script>
</body>
</html>

JavaScript Placements in HTML


 You can place or include your JavaScript code anywhere in your HTML document,
even you can also place your JavaScript code in an external file and include this file
in any HTML document to use your JavaScript code present in that file. Here are
the place, where you can include your JavaScript code:
in the <head> .. </head> section
in the <body> .. </body> section
in the <body> .. </body> and <head> .. </head> sections
in an external file and then include this file in the <head> .. </head> section

JavaScript Code in Head


Here is an example, shows how to place JavaScript code in the head section of an HTML
document:
<html>
<head>
<script type="text/javascript">
function fun1()
{
alert("Hello JavaScript")
}

</script>
</head>
<body>
<input type="button" onclick="fun1()" value="click here" />
</body>
</html>

JavaScript Code in Body


Here is an example, shows how to place your JavaScript code in body section in an HTML
document:
<html>
<head>
</head>
<body>
<script type="text/javascript">
document.write("Hello JavaScript")
</script>
<p>Hello Browser, I am HTML </p>
</body>
</html>

JavaScript Code in Body and Head


Here is an example, shows how to place your JavaScript code in body and head sections in
your HTML document:
<html>
<head>
<script type="text/javascript">
function fun1()
{
alert("Hello HTML")
}
</script>
</head>
<body>
<script type="text/javascript">
document.write("Hello HTML")
</script>
<br/>
<input type="button" onclick="fun1()" value="Click Here" />
</body>
</html>

JavaScript Code in External File


 You can also use your JavaScript code from an external file. Here is an example,
shows how to use your JavaScript code placed in external file to any HTML
document. This example, shows how to include external JavaScript file in an HTML
document/file:

<html>
<head>
<script type="text/javascript" src="filename.js" ></script>
</head>
<body>
...
...
...
</body>
</html>
 This is the most preferred and safe way to use your all JavaScript code from an
external file. Because if you want to use same JavaScript code in multiple HTML
file, then this is the most preferred way.

 You can write all your JavaScript code in a simple text file having name
like myjavascript.js. Use .js extension after the filename.

 Now you can include this file in any HTML document to use all the code present in
that file. And later if you want to change the JavaScript code, you only have to
make changes in a single file (say myjavascript.js), and all the HTML document
automatically changes.

 Here is an example, Let's assume that this JavaScript code is saved in a file
named filename.js, containing the following JavaScript code:
function fun1()
{
alert("Hello HTML")
}

 Now we are going to include the above JavaScript file filename.js in the following
HTML document:
<html>
<head>
<script type="text/javascript" src="filename.js" ></script>
</head>
<body>
<input type="button" onclick="fun1()" value="Click Here" />
</body>
</html>
 Now after including the JavaScript file in the above HTML document, the code will
become like this:
<html>
<head>
<script>
function fun1()
{
alert("Hello HTML")
}
</script>
</head>
<body>
<input type="button" onclick="fun1()" value="Click Here" />
</body>
</html>

JavaScript Statements
 A computer program is a list of "instructions" to be "executed" by a computer.
 In a programming language, these programming instructions are called statements.
 A JavaScript program is a list of programming statements.
 JavaScript statements are composed of: Variables, Operators,
Expressions, Keywords, and Comments.
 Example: document.getElementById("demo").innerHTML = "Hello Dolly.";
This statement tells the browser to write "Hello Dolly." inside an HTML
element
with id="demo":
 Semicolons separate JavaScript statements.
 Add a semicolon at the end of each executable statement

JavaScript Comments
JavaScript comments can be used to explain JavaScript code, and to make it more
readable.
There are two types of comments in JavaScript which are:
 Single Line Comments
 Multi-line comments

JavaScript Single Line Comments


 Every text after // is single line comment. In other word, single line comment starts
with //. Here is an example, uses single line comment
 Single line comments start with //.
 Any text between // and the end of the line will be ignored by JavaScript (will not
be executed).
 This example uses a single-line comment before each code line:
<html>
<body>

<h1 id="myH"></h1>
<p id="myP"></p>

<script>
// Change heading:
document.getElementById("myH").innerHTML = "JavaScript Comments";

// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";
</script>
</body>
</html>

JavaScript Multi-line Comments


Every text starts with /* and ends with */, are multi-line comments, no matter how many
lines taken. In other words, multi-line comments in JavaScript starts with /* and ends
with */. Here is an example:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Multiline Comment Example</title>
</head>
<body>
<p id="comment_para3">I am a paragraph</p>
<div id="comment_div3">I am a div</div>
<p>
<input type="button" onclick="comment_fun3()" value="Click Here"/>
</p>
<script>
/*
The code given below will change
the paragraph having id, "comment_para1",
and the div having id, "comment_div3"
*/
function comment_fun3()
{
document.getElementById("comment_para3").innerHTML = "Hello Aditya";
document.getElementById("comment_div3").innerHTML = "How are you?";
}
</script>

</body>
</html>

JavaScript Variable:-
 Variables are containers for storing data (storing data values).

4 Ways to Declare a JavaScript Variable:


1. Using var
2. Using let
3. Using const
4. Using nothing

Variable var:
Eg:
var x = 5;
var y = 6;
var z = x + y;

1. var variable can be redeclared


2. var variable have outside block scope

Variable let:
Eg:
let x = 5;
let y = 6;
let z = x + y;

 The let keyword was introduced in ES6 (2015).


 Variables defined with let cannot be Redeclared.
 Variables defined with let must be Declared before use.
 Variables defined with let have Block Scope.

Variable const:
const x = 5;
const y = 6;
x=x+y;

 The let keyword was introduced in ES6 (2015)


 Variables defined with const cannot be Redeclared.
 Variables defined with const cannot be Reassigned.
 Variables defined with const have Block Scope.

The general rules for constructing names for variables (unique identifiers) are:
 Names can contain letters, digits, underscores, and dollar signs.
 Names must begin with a letter.
 Names can also begin with $ and _ (but we will not use it in this tutorial).
 Names are case sensitive (y and Y are different variables).
 Reserved words (like JavaScript keywords) cannot be used as names.

JavaScript Operators
Operators in JavaScript, are used to perform some mathematical or logical
manipulations. There are following types of operators available in JavaScript:
 Arithmetic Operators
 Assignment Operators
 Comparison Operators
 Logical (Relational) Operators

JavaScript Arithmetic Operators


JavaScript arithmetic operators are used to perform arithmetical task. Here, the
following table lists the arithmetic operators available in JavaScript:
Operator Meaning

+ This operator adds two operands

- This operator subtracts second operand from the first

/ This operator divide numerator by denominator

* This operator multiply both operands

% This is a modulus operator, used to calculate the remainder

This is a decrement operator, decreases integer value by


--
one

This is a increment operator, increases integer value by


++
one

Important - JavaScript addition operator (+) works for numeric as well as strings. For
example, "a" + 20 will give "a20"

Example
Here is an example, uses all JavaScript arithmetic operators:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Arithmetic Operators Example</title>
<script type="text/javascript">
function operator_fun1()
{
var num1 = 22;
var num2 = 10;
var res;
res = num1 + num2;
document.getElementById("operator_sp1").innerHTML = res;
res = num1 - num2;
document.getElementById("operator_sp2").innerHTML = res;
res = num1 * num2;
document.getElementById("operator_sp3").innerHTML = res;
res = num1 / num2;
document.getElementById("operator_sp4").innerHTML = res;
res = num1 % num2;
document.getElementById("operator_sp5").innerHTML = res;
res = ++num1;
document.getElementById("operator_sp6").innerHTML = res;
res = --num1
document.getElementById("operator_sp7").innerHTML = res;
res = num1++;
document.getElementById("operator_sp8").innerHTML = res;
res = num1--;
document.getElementById("operator_sp9").innerHTML = res;
}
</script>
</head>
<body>
<p>
<span id="operator_sp1">Output 1</span><br/>
<span id="operator_sp2">Output 2</span><br/>
<span id="operator_sp3">Output 3</span><br/>
<span id="operator_sp4">Output 4</span><br/>
<span id="operator_sp5">Output 5</span><br/>
<span id="operator_sp6">Output 6</span><br/>
<span id="operator_sp7">Output 7</span><br/>
<span id="operator_sp8">Output 8</span><br/>
<span id="operator_sp9">Output 9</span>
</p>
<input type="button" onclick="operator_fun1()" value="Click Here" />
</body>
</html>
JavaScript Comparison and Logical Operator
JavaScript comparison and logical operators are basically used to test for true or false.

JavaScript Comparison Operators


JavaScript comparison operators are basically used in logical statements which is to
determine the equality or difference between variables or values. The following table lists
the comparison operators available in JavaScript:
Operator Name

== equal to

=== equal value and equal type

!= not equal

!== not equal value or not equal type

< less than

> greater than

<= less than or equal to

>= greater than or equal to

How to use Comparison Operators in JavaScript


JavaScript comparison operators can be used in conditional statements to compare the
values and takes actions depending upon the result. Here is an example:
if (marks > 90)
text = "Excellent";

JavaScript Logical Operators


JavaScript logical operators are used to determine the logic between the variables or
values. The following table lists the logical operators available in JavaScript:
Operator Name

|| Or

&& And
! Not

JavaScript Data Types:

JavaScript has 8 Datatypes

1. String
2. Number
3. Bigint
4. Boolean
5. Undefined
6. Null
7. Symbol
8. Object

The Object Datatype

The object data type can contain:

1. An object
2. An array
3. A date

Examples:
// Numbers:
let length = 16;
let weight = 7.5;

// Strings:
let color = "Yellow";
let lastName = "Johnson";

// Booleans
let x = true;
let y = false;

// Null

The special null value does not belong to any of the types described
above.
It forms a separate type of its own which contains only the null value:
let age = null;

// Undefined

If a variable is declared, but not assigned, then its value is undefined:


let age;
alert(age); // shows "undefined"
//JavaScript Symbol
The JavaScript ES6 introduced a new primitive data type called Symbol. Symbols
are immutable (cannot be changed) and are unique. For example,
// two symbols with the same description

const value1 = Symbol('hello');


const value2 = Symbol('hello');

document.write(value1 === value2); // false

// Object:
const person = {firstName:"John", lastName:"Doe"};

// Array object:
const cars = ["Saab", "Volvo", "BMW"];

// Date object:
const date = new Date("2022-03-25");

JavaScript Objects
 In real life, a car is an object.
 A car has properties like weight and color, and methods like start and stop:
Object Properties Methods

car.name = Fiat car.start()

car.model = 500 car.drive()

car.weight = 850kg car.brake()

car.color = white car.stop()

 All cars have the same properties, but the property values differ from car to car.
 All cars have the same methods, but the methods are performed at different times.

Object Definition
JavaScript object is a non-primitive data-type that allows you to store multiple
collections of data.

Example
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
 Spaces and line breaks are not important. An object definition can span multiple
lines:
(or)
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};

Accessing Object Properties


 You can access object properties in two ways:

1. Using dot Notation


Syntax: objectName.key
For example,
const person = {
name: 'John',
age: 20,
};
// accessing property
document.write(person.name);

2. Using bracket Notation


Syntax: objectName["propertyName"]
const person = {
name: 'John',
age: 20,
};

// accessing property
document.write (person["name"]); // John

Object Methods
 Objects can also have methods.
 Methods are actions that can be performed on objects.
 Methods are stored in properties as function definitions.
Example
<script>
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};

// Display data from the object:


document.getElementById("demo").innerHTML=person.fullName();
</script>

JavaScript Conditional Statements


 JavaScript conditional statements or decision making statements are used to perform
particular actions based on the given conditions.
 You will learn all about conditional statements in detail divided into the following
three tutorials:
 if Statement
 if-else Statement
 switch Statement

JavaScript Conditional Statements Example


Here is an example, demonstrates conditional statement in JavaScript:
<html>
<head>
</head>
<body>
<script>
var a=10;
if(a>10)
{
document.write("a is big");
}
</script>
</body>
</html>

JavaScript if-else Statement


The if-else statement in JavaScript is used to execute the code that is written in the if
statement, if the specified condition is true. Otherwise, the code written in the else
statement is executed.

JavaScript if-else Statement Example


Here is an example demonstrates if-else statement in JavaScript.
<html>
<head>
</head>
<body>
<script>
var a=10;
if(a>10)
{
alert("a is big");
}
else
{
alert("b is big");
}
</script>
</body>
</html>

JavaScript switch Statement


The switch statement in JavaScript is used to select a particular group of statements to be
executed among several other groups of statements.

JavaScript switch Statement Example


Here is an example illustrates how to use switch statement in JavaScript:
<!DOCTYPE HTML>
<html>
<head>
<title>JavaScript switch Statement</title>
</head>
<body>

<h3>JavaScript switch Statement Example</h3>


<script type="text/javascript">
var mychar = "C";
document.write("Checking the character...<br/>");
switch(mychar)
{
default: document.write(mychar + " is a consonant.");
break;
case "A": document.write(mychar + " is a vowel.");
break;
case "E": document.write(mychar + " is a vowel.");
break;
case "I": document.write(mychar + " is a vowel.");
break;
case "O": document.write(mychar + " is a vowel.");
break;
case "U": document.write(mychar + " is a vowel.");
break;
}
document.write("<br/>Done!");
</script>
</body>
</html>

JavaScript Loops
Loops or iteration statements are control flow statements that allows you to execute
group of statements several number of times.
There are the following three loops provided by JavaScript:
 for Loop
 while Loop
 do-while Loop
Here is an example. Instead of this code fragment:
fruits = fruits + fruit[0] + "<br>";
fruits = fruits + fruit[1] + "<br>";
fruits = fruits + fruit[2] + "<br>";
fruits = fruits + fruit[3] + "<br>";
fruits = fruits + fruit[4] + "<br>";
fruits = fruits + fruit[5] + "<br>";
You can write :
for(i = 0; i < fruit.length; i++)
{
fruits = fruits + fruit[i] + "<br>";
}

JavaScript Loops Example


Here is an example demonstrates loop in JavaScript.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Loops Example</title>
<script>
var num;
var i;
for (i = 1; i <= 10; i++)
{
num = num + i + "<br>";
}
document.write(num);
</script>
</head>
<body>
</body>
</html>

JavaScript for Loop


 The for loop in JavaScript is used to execute a block of code or group of statements
multiple times based on the given/particular condition.
 Here is the general form to use for loop in JavaScript:
for(initialization; condition-checker; incrementation)
{
// block of code, to be executed here
}
Here is the explanation:
 initialization - This part is used to initialize the loop variable. This part is executed
first, after the execution, loop control never executes this part. After executing the
initialization part, loop control transfers to the condition-checker part
 condition-checker - This part is executed to check whether the condition evaluates
to true or false. If true, then the loop control transfers to the body of the loop to
execute the given block of code, otherwise if false, then the loop exits. Every time
loop control transfers to the condition-checker part after incrementation part, except
at the first time. At first time, loop control transfers to condition-checker part after
initialization part

 incrementation - This part is executed every time after running the block of code
present inside the loop. This part is is to increment or decrement the loop variable

JavaScript for Loop Example


Here is an example illustrates how to use for loop in JavaScript:
<html>
<head>
<title>JavaScript for Loop</title>
</head>
<body>

<h3>JavaScript for Loop Example</h3>


<script type="text/javascript">
var num = 2;
document.write("Printing the table of " + num + "<br/>");
var i;
for(i=1; i<=10; i++)
{
document.write("<i>"+num*i +"</i>"+ "<br/>");
}
document.write("Done!");
</script>
</body>
</html>

JavaScript while Loop


 The while loop in JavaScript is used when you want to check the condition at
the start of the loop and then the group of statements that is to be executed is
specified after the condition.
 Here is the general form to use while loop in JavaScript:
while(condition-checker)
{
// block of code to be executed here
incrementation;
}
JavaScript while Loop Example
Here is an example of while loop in JavaScript:
<!DOCTYPE HTML>
<html>
<head>
<title>JavaScript while Loop</title>
</head>
<body>
<h3>JavaScript while Loop Example</h3>
<script type="text/javascript">
var num = 2;
document.write("Printing the table of " + num + "<br/>");
var i = 1;
while(i<=10)
{
document.write(num*i + "<br/>");
i++;
}
document.write("Done!");
</script>
</body>
</html>
JavaScript do-while Loop
 The do-while loop in JavaScript is used in the case where you want a group
of statements to be executed at least once.
 Since the condition is placed at the end of the loop in case of do-while loop in
JavaScript, therefore you can use this loop to executed group of statements at
least once.
 Here is the general form of do-while loop in JavaScript:

do {
// block of code to be executed here
// incrementation
} while(condition);
JavaScript do-while Loop Example
Here is an example illustrates how to use do-while loop in JavaScript:
<!DOCTYPE HTML>
<html>
<head>
<title>JavaScript do-while Loop</title>
</head>
<body>
<h3>JavaScript do-while Loop Example</h3>
<script type="text/javascript">
var num = 2;
document.write("Printing the table of " + num + "<br/>");
var i = 1;
do
{
document.write(num*i + "<br/>");
i++;
} while(i<=10);
document.write("Done!");

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

JavaScript Break and Continue


JavaScript break and continue statement/keyword is used to control the loop.

JavaScript break Statement


JavaScript break statement is used to exit from the loop when the required condition is
met. Here is an example uses break statement to exit the loop:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Break Statement</title>
</head>
<body>
<p>Loop breaks when i becomes equal to 5</p>
<p id="break_statement_para1"></p>
<script>
var text = "";
var i;
for(i = 0; i < 10; i++)
{
if(i === 5)
{
break;
}
text += + i + "<br>";
}
document.getElementById("break_statement_para1").innerHTML = text;
</script>
</body>
</html>

JavaScript continue Statement


JavaScript continue statement is used to skip the remaining part of code and goes to the
condition-checker part, if the required condition is met. Here is an example uses continue
statement to skip one iteration of the loop:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript continue Statement Example</title>
</head>
<body>
<p>Loop breaks when i becomes equal to 5</p>
<p id="continue_statement_para1"></p>
<script>
var text = "";
var i;
for(i = 0; i < 10; i++)
{
if(i === 5)
{
continue;
}
text += + i + "<br>";
}
document.getElementById("continue_statement_para1").innerHTML =
text;
</script>
</body>
</html>

JavaScript Arrays:

 An array is an object that can store multiple values at once. For example,
 In JavaScript, an array is an ordered list of values. Each value is called
an element specified by an index:
An array is an object that can store multiple values at once. For example,
const words = ['hello', 'world', 'welcome'];
Here, words is an array. The array is storing 3 values.

A JavaScript array has the following characteristics:


1. First, an array can hold values of mixed types. For example, you can have an
array that stores elements with the types number, string, boolean, and null.
2. Second, the size of an array is dynamic and auto-growing. In other words, you
don‟t need to specify the array size up front.
Create an Array
You can create an array using two ways:
1. Using an array literal
The easiest way to create an array is by using an array literal []. For example,

Const array1 = ["eat", "sleep"];

2. Using the new keyword


You can also create an array using JavaScript's new keyword.
const array2 = new Array("eat", "sleep");
In both of the above examples, we have created an array having two elements.
Here are more examples of arrays:
// empty array
const myList = [ ];

// array of numbers
const numberArray = [ 2, 4, 6, 8];

// array of strings
const stringArray = [ 'eat', 'work', 'sleep'];

// array with mixed data types


const newData = ['work', 'exercise', 1, true];

Access Elements of an Array


You can access elements of an array using indices (0, 1, 2 …). For example,
const myArray = ['h', 'e', 'l', 'l', 'o'];
// first element
document.write (myArray[0]); // "h"

// second element
document.write (myArray[1]); // "e"

Add an Element to an Array


You can use the built-in method push() and unshift() to add elements to an array.
The push() method adds an element at the end of the array. For example,
let dailyActivities = ['eat', 'sleep'];

// add an element at the end


dailyActivities.push('exercise');

document.write(dailyActivities); // ['eat', 'sleep', 'exercise']

Change the Elements of an Array


You can also add elements or change the elements by accessing the index value.
let dailyActivities = [ 'eat', 'sleep'];

// this will add the new element 'exercise' at the 2 index


dailyActivities[2] = 'exercise';

document.write(dailyActivities); // ['eat', 'sleep', 'exercise']

Suppose, an array has two elements. If you try to add an element at index 3 (fourth
element), the third element will be undefined. For example,

let dailyActivities = [ 'eat', 'sleep'];

// this will add the new element 'exercise' at the 3 index


dailyActivities[3] = 'exercise';

document.write(dailyActivities); // ["eat", "sleep", undefined, "exercise"]

Remove an Element from an Array


You can use the pop() method to remove the last element from an array.
The pop() method also returns the returned value. For example,

let dailyActivities = ['work', 'eat', 'sleep', 'exercise'];

// remove the last element


dailyActivities.pop();
document.write (dailyActivities); // ['work', 'eat', 'sleep']
// remove the last element from ['work', 'eat', 'sleep']
const removedElement = dailyActivities.pop();

//get removed element


document.write (removedElement); // 'sleep'
document.write (dailyActivities); // ['work', 'eat']

Array Methods
In JavaScript, there are various array methods available that makes it easier to perform
useful calculations.
Some of the commonly used JavaScript array methods are:
Method Description

concat() joins two or more arrays and returns a result

indexOf() searches an element of an array and returns its position

find() returns the first value of an array element that


passes a test
findIndex() returns the first index of an array element that passes a test

forEach() calls a function for each element

includes() checks if an array contains a specified element

push() adds a new element to the end of an array and returns the
new length of an array
unshift() adds a new element to the beginning of an array and returns
the new length of an array
pop() removes the last element of an array and returns the
removed element
shift() removes the first element of an array and returns the
removed element
sort() sorts the elements alphabetically in strings and in ascending
order
slice() selects the part of an array and returns the new array

splice() removes or replaces existing elements and/or adds new


elements
2.2 OOPS Aspects of JavaScript:-
 Object-oriented programming (OOP) is a programming paradigm used by
developers to structure software applications into reusable pieces of code and
blueprints using objects.
 OOP makes it easier to create and manage many parts of your application in
isolation and connect them without making them depend on one another.

Features of OOP:-
1. Abstraction
Abstraction in OOP is the process of exposing only the necessary functions to
the user while hiding the complex inner workings to make the programs
easier to use and understand.
2. Encapsulation
Encapsulation is the process of bundling related code into a single unit.
Encapsulation makes it impossible for other parts of the code to manipulate or
change how the bundled part of the application works unless you explicitly go
into that unit and change them.
3. Inheritance
Inheritance in OOP reduces code duplication, enabling you to build a part of
your application on another by inheriting properties and methods from that
part of the application.
4. Polymorphism
In programming, polymorphism is a term used to describe a code or program
that can handle many types of data by returning a response or result based on
the given data.

JavaScript Objects
 An object in JavaScript is an unordered collection of key-value pairs, also
known as properties and values.
 Object keys can be a string value, while the values can be any type. Here are
some examples:
 String
 Number
 Boolean
 Array
Creating Objects
 In JavaScript, you have the following three options to create an object:
 Define and create a single object, with the keyword new.
 Define and create a single object, using an object literal.
Define an object constructor, and then create objects of the constructed type.

Creating an object using keyword new


const car = new object(
{
name: 'Ford', year: 2015,
color: 'red',
description: function ()
{
return `${this.name} - ${this.year} -
${this.color}`;
}
});
Creating an object using literal
const car =
{
name: 'Ford', year: 2015,
color: 'red',
description: function ()
{
return `${this.name} - ${this.year} -
${this.color}`;
}
}

 The code above declares a car object with name, year, color, and
a description function as its properties.

Creating an object using Constructor Function


function car(name, color)
{
this.name=name;
this.color=color,
}
var car1=new car(„Audi‟, „Red‟);
var car2=new car(„Benz‟, „White‟);
document.write(car1.name+car1.color);
document.write(car2.name+car2.color);

Accessing Object Properties


 There are two ways to access an object property in JavaScript;
1. Using the Dot Notation
The following example shows how to access object properties using dot
notation.
const country =
{
name: 'Spain',
population: 4000000,
description: function ()
{
return `${this.name} - ${this.population}`;
}
}
 If you have an object like the one shown above, you can use the
format objectName.keyName, which should return the value of the given key:
document.write(country.name); // returns 'Spain'

2. Using the Array Notation


const job =
{
name: „jegan‟,
role: "Software Engineer",
'salary': 200000,
};
 If you have an object like the one above, you can use the
format objectName[keyName], which should return the value of the given key:
document.write(job[role]); // returns 'Software Engineer'
 Additionally, you can only access the salary property using the array notation.
Trying to get it with the dot notation will return an error:
document.write (job.'salary');

Modifying Object Properties


Editing Properties: You can use the assignment = operator to modify object values.
Here is an example:
const person =
{
name: "John",
age: 30,
job: "Software Developer",
country: "Nigeria",
car: "Ford",
description: function ()
{
return `${this.name} - ${this.age} - ${this.job.role}
- ${this.country.name} - ${this.car.name}`;
},
};
 You can also change the value of name in the above object:
person.name = "Smith Doe";
document.write(person.name); // returns "Smith Doe"

Adding New Properties


 One of the significant differences between objects in other languages and
objects in JavaScript is the ability to add a new property to an object after
creation.
 To add a new property to an object, you use the dot notation:
person.race = "Asian"; // adding a new `race` property
document.write(person.race); // returns "Asian"
 The code above adds a new race property with the value "Asian".

Deleting Object Properties


 JavaScript allows you to delete properties from an object by using
the delete keyword:
delete person.race;
document.write (person.race); // returns 'undefined
 The code above deletes the race property, and accessing the race property will
return undefined.

Checking Properties
 Before adding to or deleting properties from an object, it is an excellent idea
to determine whether the property exists on the object.
 To determine whether a property exists on an object, you can use
the in keyword:
document.write('name' in person) // returns true
document.write('race' in person) // returns false
 The code above returns true for the name check because the name exists
and false for the deleted race property.

Class
 In programming, a class is a structure defined by a programmer that is then
used to create multiple objects of the same type.
 For example, if you are building an application that handles various cars, you
can create a Car class that has the essential functions and properties that apply
to all vehicles.
 Then, you can use this class to make other cars and add properties and
methods that are specific to each vehicle to them.
Creating Classes
class Job
{
constructor(name, role, salary)
{
this.name=name,
this.role = role;
this.salary = salary;

}
}

Object Creation
var job1 = new Job( “jegan", “Associate Professor”,200000) var job2 =
new Job( “Deepa", “Assistant Professor”,100000)
The this Keyword
 In the above example, the this keyword refers to any object created with
the Job class. Therefore, inside the constructor method, this.role =
role; means "define the role property of this object you're creating as any
value given to the constructor".
 Also, note that the initial values you give must be in order when creating a
new Job object.

Class Methods
 When creating classes, you can add as many properties as you like. For
example, if you have a Vehicle class, aside from basic properties
like type, color, brand, and year, you probably also want to have methods
like start, stop, pickUpPassengers, and dropOffPassengers.
 To add methods inside classes, you can add them after
the constructor function:
class Person
{
constructor(name)
{
this.name = name;
}
// defining method
greet()
{
console.log(`Hello ${this.name}`);
}
}
let person1 = new Person('John'); // accessing property
console.log(person1.name); // John
// accessing method
person1.greet(); // Hello John
Class Inheritance
 Inheritance enables you to define a class that takes all the functionality from a
parent class and allows you to add more.
 Using class inheritance, a class can inherit all the methods and properties of
another class.
 Inheritance is a useful feature that allows code reusability.
 To use class inheritance, you use the extends keyword. For example,

class Person // parent class


{
constructor(name)
{
this.name = name;
}
greet()
{
console.log(`Hello ${this.name}`);
}
}

class Student extends Person // inheriting parent class


{

}
let student1 = new Student('Jack');
student1.greet();

JavaScript super() keyword


// parent class
class Person
{
constructor(name)
{
this.name = name;
}
greet()
{
console.log(`Hello ${this.name}`);
}
}

class Student extends Person // inheriting parent class


{
constructor(name)
{
console.log("Creating student class");

// call the super class constructor and pass in the name parameter
super(name);
}
}
let student1 = new Student('Jack');
student1.greet()

Overriding Method or Property


class Person // parent class
{
constructor(name)
{
this.name = name;
this.occupation= "unemployed";
}

greet()
{
console.log(`Hello ${this.name}.`);
}

class Student extends Person // inheriting parent class


{
constructor(name)
{
// call the super class constructor and pass in the
name parameter
super(name);

// Overriding an occupation property


this.occupation = 'Student';
}

// overriding Person's method


greet()
{
console.log(`Hello student ${this.name}.`);
console.log('occupation: ' + this.occupation);
}
}
let p = new Student('Jack');
p.greet();

2.3 Memory Usage in JavaScript


 JavaScript automatically allocates memory when objects are created and frees
it when not in use anymore (garbage collection).
 C has memory-management techniques like malloc() and free(). It doesn‟t
mean that we don‟t need to worry about memory management in JavaScript.

Memory Life Cycle:


 Irrespective of the programming language, the memory life cycle follows the
following stages:
1. Allocates the memory we need: JavaScript allocates memory to the object
created.
2. Use the allocated memory.
3. Release the memory when not in use: Once the allocated memory is
released, it is used for other purposes. It is handled by a JavaScript engine.

 The second stage is the same for all the languages. However, the first and last
stage is implicit in high-level languages like JavaScript.

JavaScript engines have two places to store data:


 Stack: It is a data structure used to store static data. Static data refers to data
whose size is known by the engine during compile time. In JavaScript, static
data includes primitive values like strings, numbers, boolean, null, and
undefined. References that point to objects and functions are also included. A
fixed amount of memory is allocated for static data. This process is known
as static memory allocation.
 Heap: It is used to store objects and functions in JavaScript. The engine
doesn‟t allocate a fixed amount of memory. Instead, it allocates more space as
required.

Allocation in JavaScript
 Value initialization
 In order to not bother the programmer with allocations, JavaScript will
automatically allocate memory when values are initially declared.
const n = 123; // allocates memory for a number
const s = "azerty"; // allocates memory for a string
const o = { a: 1, b: null, }; // allocates memory for an object and
contained values
// (like object) allocates memory for the array and contained values

const a = [1, null, "abra"];

function f(a)
{
return a + 2;
} // allocates a function (which is a callable object)

 Release when the memory is not needed anymore


 The majority of memory management issues occur at this phase. The most
difficult aspect of this stage is determining when the allocated memory is no
longer needed.
 Low-level languages require the developer to manually determine at which
point in the program the allocated memory is no longer needed and to release
it.
 Some high-level languages, such as JavaScript, utilize a form of automatic
memory management known as garbage collection (GC). The purpose of a
garbage collector is to monitor memory allocation and determine when a
block of allocated memory is no longer needed and reclaim it.
2.4 JavaScript Functions:

 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).

Syntax

 A JavaScript function is defined with the function keyword, followed by


a name, followed by parentheses ().

 Function names can contain letters, digits, underscores, and dollar signs (same
rules as variables).

 The parentheses may include parameter names separated by commas:


(parameter1, parameter2, ...)

 The code to be executed, by the function, is placed inside curly brackets: {}

function name(parameter1, parameter2, parameter3)


{
// code to be executed
}

 Function parameters are listed inside the parentheses () in the function


definition.

 Function arguments are the values received by the function when it is


invoked.

Function Invocation (Or) Calling

 The code inside the function will execute when "something" invokes (calls) the
function:

 When an event occurs (when a user clicks a button)


 When it is invoked (called) from JavaScript code
 Automatically (self invoked)

Function Parameters
A function can also be declared with parameters. A parameter is a value that is passed
when declaring a function.
function functionName(parameter1, parameter2, parameter3) {
// code to be executed
}

Parameter Rules
JavaScript function definitions do not specify data types for parameters.
JavaScript functions do not perform type checking on the passed arguments.
JavaScript functions do not check the number of arguments received.
Example 1:
function greet(name) {
document.write("Hello " + name + ":)");
}
// variable name can be different
var name = prompt("Enter a name: ");
// calling function
greet(name);
Example 2:
function add(a, b) {
document.write (a + b);
}
// calling functions
add(3,4);
add(2,9);

Function Return
 When JavaScript reaches a return statement, the function will stop executing.
 If the function was invoked from a statement, JavaScript will "return" to execute the
code after the invoking statement.
 Functions often compute a return value. The return value is "returned" back to the
"caller":

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Functions</h2>

<p>This example calls a function which performs a calculation, and


returns the result:</p>

<p id="demo"></p>

<script>
function myFunction(p1, p2) {
return p1 * p2;
}
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>

</body>
</html>

Benefits of Using a Function


 Function makes the code reusable. You can declare it once and use it multiple
times.
 Function makes the program easier as each small task is divided into a function.
 Function increases readability.

Constructor:-
In JavaScript, a constructor function is used to create objects. For example,

// constructor function
function Person ()
{
this.name = 'John',
this.age = 23
}

// create an object
const person = new Person();

 In the above example, function Person() is an object constructor function.


 To create an object from a constructor function, we use the new keyword.

Create Multiple Objects with Constructor Function


<html>
<body>

<h2>JavaScript Object Constructors</h2>

<p id="demo"></p>
<p id="demo1"></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 myFather = new Person("John", "Doe", 50, "blue");
const myFather1 = new Person("Jegan", "Deepa", 50, "blue");

// Display age
document.getElementById("demo").innerHTML ="My father is " + myFather.age +
".";

document.getElementById("demo1").innerHTML ="My father is " + myFather1.age


+ ".";
</script>

</body>
</html>

JavaScript this Keyword:


In JavaScript, when this keyword is used in a constructor function, this refers to the
object when the object is created. For example,

// constructor function
function Person () {
this.name = 'John',
}

// create object
const person1 = new Person();

// access properties
document.write (person1.name); // John

JavaScript Constructor Function Parameters


<html>
<body>

<h2>JavaScript Object Constructors</h2>

<p id="demo"></p>
<p id="demo1"></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 myFather = new Person("John", "Doe", 50, "blue");
const myFather1 = new Person("Jegan", "Deepa", 50, "blue");

// Display age
document.getElementById("demo").innerHTML ="My father is " +
myFather.age + ".";

document.getElementById("demo1").innerHTML ="My father is " +


myFather1.age + ".";
</script>

</body>
</html>

AJAX

 AJAX is a new technique for creating faster web pages and has replaced the
way conventional web applications used to transmit information.

 AJAX can be defined as a tool or technique that uses a group of technologies


such as HTML, XML, CSS, and JavaScript to create dynamic and better web
pages

 An acronym for Asynchronous JavaScript and XML, AJAX is not a


programming language but a technique to create faster and more responsive
web-based applications.

 Ajax uses XHTML for content, CSS for presentation, along with Document
Object Model and JavaScript for dynamic content display.

 Conventional web applications transmit information to and from the sever


using synchronous requests. It means you fill out a form, hit submit, and get
directed to a new page with new information from the server.

 With AJAX, when you hit submit, JavaScript will make a request to the
server, interpret the results, and update the current screen. In the purest sense,
the user would never know that anything was even transmitted to the server.
 XML is commonly used as the format for receiving server data, although any
format, including plain text, can be used.

 AJAX is a web browser technology independent of web server software.

 A user can continue to use the application while the client program requests
information from the server in the background.

 Intuitive and natural user interaction. Clicking is not required, mouse


movement is a sufficient event trigger.

 Data-driven as opposed to page-driven.

AJAX is Based on Open Standards


AJAX is based on the following open standards −
 Browser-based presentation using HTML and Cascading Style Sheets
(CSS).
 Data is stored in XML format and fetched from the server.
 Behind-the-scenes data fetches using XMLHttpRequest objects in the
browser.
 JavaScript to make everything happen.

AJAX - Technologies
AJAX cannot work independently. It is used in combination with other technologies
to create interactive webpages.
1. JavaScript
2. DOM
3. CSS
4. XML HttpRequest
AJAX - Examples

1. Google Maps

 A user can drag an entire map by using the mouse, rather than
clicking on a button.

https://maps.google.com/

2. Gmail

 Gmail is a webmail built on the idea that emails can be more


intuitive, efficient, and useful.

https://gmail.com/

Difference between AJAX and Conventional CGI Program


 While trying AJAX example, there is no discontinuity and you get
the response very quickly, but when you try the standard GCI
example, you would have to wait for the response and your page
also gets refreshed.

https://www.tutorialspoint.com/ajax/ajaxCGI.php?num1=4&num2=6&result=&semajax=Standard

AJAX - Browser Support


 All the available browsers cannot support AJAX. Here is a list of major
browsers that support AJAX.

 Mozilla Firefox 1.0 and above.


 Netscape version 7.1 and above.
 Apple Safari 1.2 and above.
 Microsoft Internet Explorer 5 and above.
 Konqueror.
 Opera 7.6 and above.

NOTE − When we say that a browser does not support AJAX, it simply means
that the browser does not support the creation of Javascript object –
XMLHttpRequest object.

 Ajax allows web pages to be updated asynchronously by exchanging


small amounts of data with the server behind the scenes.
 For implementing Ajax, only be aware of XMLHttpRequest object. It is an
object used to exchange data with the server behind the scenes.

The keystone of AJAX is the XMLHttpRequest object.

1. Create an XMLHttpRequest object


2. Define a callback function
3. Open the XMLHttpRequest object and Send a Request to a server

Create an XMLHttpRequest object

req = new XMLHttpRequest();

Define a callback function

 A callback function is a function passed as a parameter to another


function.

 In this case, the callback function should contain the code to execute
when the response is ready.

xhttp.onload = function()
{
// What to do when the response is ready
}

Send a Request to a server

 There are two types of methods open() and send(). Uses of these
methods explained below.

req.open("GET", "abc.php", true);

req.send();

 The above two lines described the two methods. req stands for the
request, it is basically a reference variable.

 The GET parameter is as usual one of two types of methods to send the
request. Use POST as well depending upon whether send the data
through POST or GET method.

 The second parameter being the name of the file which actually handles
the requests and processes them.
 The third parameter is true, it tells that whether the requests are
processed asynchronously or synchronously.

 It is by default true which means that requests are asynchronous. The


open() method prepares the request before sending it to the server.

 The send method is used to send the request to the server.

 Sending the parameter through getting or POST request. The syntax is


given below

Syntax:-
const xhttp = new XMLHttpRequest(); // Create an XMLHttpRequest object

xhttp.onload = function() // Define a callback function


{
// Here you can use the Data
}

xhttp.open("GET", "ajax_info.txt"); // Send a request


xhttp.send();

Example:-
<html>
<body>

<h2>The XMLHttpRequest Object</h2>

<div id="demo">
<p>Let AJAX change this text.</p>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>

<script>
function loadDoc()
{
const xhttp = new XMLHttpRequest();
xhttp.onload = function()
{
document.getElementById("demo").innerHTML =
this.responseText;
}
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
}
</script>
</body>
</html>

Example:-

The following example demonstrates how a web page can communicate


with a web server while a user types characters in an input field:

<html>
<body>

<h2>The XMLHttpRequest Object</h2>


<h3>Start typing a name in the input field below:</h3>

<p>Suggestions: <span id="txtHint"></span></p>


<p>First name: <input type="text" id="txt1" onkeyup="showHint(this.value)">
</p>

<script>
function showHint(str)
{
if (str.length == 0)
{
document.getElementById("txtHint").innerHTML = "";
return;
}
const xhttp = new XMLHttpRequest();

xhttp.onload = function()
{
document.getElementById("txtHint").innerHTML =
this.responseText;
}
xhttp.open("GET", "gethint.php?q="+str);
xhttp.send();
}
</script>

</body>
</html>
Code explanation:

First, check if the input field is empty (str.length == 0). If it is, clear the
content of the txtHint placeholder and exit the function.

However, if the input field is not empty, do the following:

 Create an XMLHttpRequest object


 Create the function to be executed when the server response is ready
 Send the request off to a PHP file (gethint.php) on the server
 Notice that q parameter is added gethint.php?q="+str
 The str variable holds the content of the input field

You might also like