Unit-2 FSD
Unit-2 FSD
Unit – II
Front end Development
Regulation – R20
Unit – III
Frontend Development
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 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.
Advantages of JavaScript
Here are the advantages of JavaScript:
Less server interaction
More interactivity
Richer interfaces
Fast feedback to visitors
<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
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>
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>
</script>
</head>
<body>
<input type="button" onclick="fun1()" value="click here" />
</body>
</html>
<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
<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>
</body>
</html>
JavaScript Variable:-
Variables are containers for storing data (storing data values).
Variable var:
Eg:
var x = 5;
var y = 6;
var z = x + y;
Variable let:
Eg:
let x = 5;
let y = 6;
let z = x + y;
Variable const:
const x = 5;
const y = 6;
x=x+y;
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
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.
== equal to
!= not equal
|| Or
&& And
! Not
1. String
2. Number
3. Bigint
4. Boolean
5. Undefined
6. Null
7. Symbol
8. Object
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
// 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
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 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;
}
};
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>";
}
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
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 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.
// array of numbers
const numberArray = [ 2, 4, 6, 8];
// array of strings
const stringArray = [ 'eat', 'work', 'sleep'];
// second element
document.write (myArray[1]); // "e"
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,
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
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
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.
The code above declares a car object with name, year, color, and
a description function as its properties.
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,
}
let student1 = new Student('Jack');
student1.greet();
// call the super class constructor and pass in the name parameter
super(name);
}
}
let student1 = new Student('Jack');
student1.greet()
greet()
{
console.log(`Hello ${this.name}.`);
}
The second stage is the same for all the languages. However, the first and last
stage is implicit in high-level languages like JavaScript.
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
function f(a)
{
return a + 2;
} // allocates a function (which is a callable object)
Syntax
Function names can contain letters, digits, underscores, and dollar signs (same
rules as variables).
The code inside the function will execute when "something" invokes (calls) the
function:
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 id="demo"></p>
<script>
function myFunction(p1, p2) {
return p1 * p2;
}
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>
</body>
</html>
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();
<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 +
".";
</body>
</html>
// constructor function
function Person () {
this.name = 'John',
}
// create object
const person1 = new Person();
// access properties
document.write (person1.name); // John
<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;
}
// Display age
document.getElementById("demo").innerHTML ="My father is " +
myFather.age + ".";
</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 uses XHTML for content, CSS for presentation, along with Document
Object Model and JavaScript for dynamic content display.
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.
A user can continue to use the application while the client program requests
information from the server in the background.
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
https://gmail.com/
https://www.tutorialspoint.com/ajax/ajaxCGI.php?num1=4&num2=6&result=&semajax=Standard
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.
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
}
There are two types of methods open() and send(). Uses of these
methods explained below.
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.
Syntax:-
const xhttp = new XMLHttpRequest(); // Create an XMLHttpRequest object
Example:-
<html>
<body>
<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:-
<html>
<body>
<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.