0% found this document useful (0 votes)
4 views

Java Script PPT(Unit-3)

The document outlines the syllabus for Unit-3 of Web Technology, focusing on client-side scripting with JavaScript and networking concepts. It details the advantages and key components of client-side scripting, including HTML, CSS, and JavaScript, and discusses various data types and operators in JavaScript. Additionally, it introduces frameworks and libraries that facilitate client-side scripting, emphasizing the importance of interactivity and user experience in web development.

Uploaded by

Shreya Saxena
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Java Script PPT(Unit-3)

The document outlines the syllabus for Unit-3 of Web Technology, focusing on client-side scripting with JavaScript and networking concepts. It details the advantages and key components of client-side scripting, including HTML, CSS, and JavaScript, and discusses various data types and operators in JavaScript. Additionally, it introduces frameworks and libraries that facilitate client-side scripting, emphasizing the importance of interactivity and user experience in web development.

Uploaded by

Shreya Saxena
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 96

Web Technology Unit- 3

Syllabus for Unit-3


• Scripting: Java script: Introduction,
documents, forms, statements, functions,
objects, introduction to AJAX.
• Networking: Internet Addressing, InetAddress,
Factory Methods, Instance Methods, TCP/IP
Client Sockets, URL, URL Connection, TCP/IP
Server Sockets, Datagram.
6/7/2023 Prof. SHIV VEER SINGH 1
What is Client-Side Scripting
• Client-side scripting refers to the process of
writing and executing scripts or code within a
web page that runs on the user's web browser.
These scripts are typically written in languages
such as JavaScript, which is the most common
client-side scripting language. Client-side
scripting is used to enhance the functionality and
interactivity of a web page, providing a dynamic
and responsive user experience.

6/7/2023 Prof. SHIV VEER SINGH 2


Some key aspects of client-side scripting:
• Execution on the User's Device: Unlike server-side scripting, which
runs on the web server, client-side scripts execute on the user's
device (usually a web browser). This means that the user's computer
or mobile device is responsible for processing and executing the
script.
• Interactivity: Client-side scripting is used to create interactive
elements on a web page. This can include features like form
validation, dynamic content updates, user interface enhancements,
and more. It allows users to interact with a web page in real-time
without needing to refresh the entire page.
• Enhanced User Experience: By adding interactivity and dynamic
behavior, client-side scripting can significantly improve the user
experience. It makes web applications more responsive and engaging.
6/7/2023 Prof. SHIV VEER SINGH 3
Some key aspects of client-side scripting….
Reduced Server Load: Since client-side scripts execute on the user's
device, they can reduce the load on the web server. This is because
many tasks that would otherwise require server processing, such as
form validation and content updates, can be handled on the client
side.
Immediate Feedback: Client-side scripts can provide immediate
feedback to users. For example, when a user fills out a form, client-
side scripting can validate the data and provide instant feedback,
reducing the need to wait for a server response.
Offline Capabilities: With modern web technologies, client-side
applications can work offline or in low-connectivity situations,
providing continuity and a better user experience.
JavaScript is the most widely used language for client-side scripting,
but other languages like HTML, CSS, and various JavaScript libraries
and frameworks can also be employed to create rich, interactive web
applications. Client-side scripting is an essential part of modern web
development and plays a crucial role in creating dynamic and user-
friendly websites and web applications.

6/7/2023 Prof. SHIV VEER SINGH 4


Key Components of Client-Side Scripting:
• HTML (Hypertext Markup Language): The structure of a web page
is defined using HTML. HTML provides the foundation for client-
side scripting, as it creates the content and structure that the
script will manipulate.
• CSS (Cascading Style Sheets): CSS is used to define the
presentation and styling of web page elements. It complements
client-side scripting by allowing for the manipulation of the visual
appearance of elements.
• JavaScript: JavaScript is the primary language for client-side
scripting. It enables developers to add dynamic behavior, handle
user interactions, and manipulate HTML and CSS in real-time.
JavaScript can be embedded within HTML documents or loaded
from external files.
6/7/2023 Prof. SHIV VEER SINGH 5
Advantages of Client-Side Scripting:
• Improved User Experience: Interactivity and responsiveness
make web applications more user-friendly and engaging.
• Reduced Server Load: Since client-side scripts run on the
user's device, they offload processing from the server,
leading to improved performance and scalability.
• Instant Feedback: Users can receive immediate feedback
without waiting for server responses, enhancing the user
experience.
• Offline Capabilities: Modern web technologies enable
client-side applications to work offline, providing continuity
even when the internet connection is lost.

6/7/2023 Prof. SHIV VEER SINGH 6


Uses of Client-Side Scripting:
• Form Validation: Ensuring that user-submitted data meets
specific criteria before being sent to the server.
• Dynamic Content: Loading content dynamically without requiring
page refreshes.
• User Interfaces: Creating interactive elements like sliders,
accordions, and modals.
• AJAX (Asynchronous JavaScript and XML): Making asynchronous
requests to the server for data updates without reloading the
entire page.
• Data Visualization: Generating charts, graphs, and interactive
data displays.
• Cookies and Local Storage: Storing and managing data on the
user's device.
6/7/2023 Prof. SHIV VEER SINGH 7
Frameworks and Libraries:
In addition to plain JavaScript, there are numerous frameworks and libraries
available to simplify client-side scripting, such as:

• jQuery: A popular library that simplifies DOM


manipulation and AJAX requests.
• React: A JavaScript library for building user
interfaces with a component-based
architecture.
• Angular: A full-featured framework for building
complex web applications.
• Vue.js: A progressive framework for building
user interfaces with a focus on simplicity.
6/7/2023 Prof. SHIV VEER SINGH 8
Introduction to Java Script
• JavaScript is a lightweight, interpreted programming language.

• It is designed for creating network-centric applications

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

• JavaScript is the programming language of the Web.

• JavaScript is easy to learn.

6/7/2023 Prof. SHIV VEER SINGH 9


Java Script cont…

 Java Script is used insert dynamic text into HTML (ex: user
name)

 It’s get information about a user's computer (ex: browser type)

 It perform calculations on user's computer (ex: form


validation)

 Java script offers a vast standard library that has a wide variety
of functions and methods available to help in the process of
development, making the entire process easier and hassle-free

6/7/2023 Prof. SHIV VEER SINGH 10


Features of Java script
Javascript is a lightweight, cross-platform, and interpreted language.

It was developed with the main intention of DOM (Document Object Model)- to
change or modify an HTML document that will be displayed in a web
browser.) manipulation, bringing forth the era of dynamic websites.

Javascript functions are objects and can be passed in other functions as


parameters.

Can handle date and time manipulation.

Can perform Form Validation.

A compiler is not needed.


6/7/2023 Prof. SHIV VEER SINGH 11
Data Types in JavaScript's
• In JavaScript, data types represent the kind of
data you can work with in your code. JavaScript
has several primitive data types and a more
complex data type, which is the object data
type.
• 1. Number: Represents both integer and
floating-point numbers.
let n = 42;
let a = 3.141592;
6/7/2023 Prof. SHIV VEER SINGH 12
Data Types in JavaScript's…
2. String: Represents text data, enclosed in single or
double quotes.
let firstName = “SHIV";
let middleName = ‘VEER';
let lastName = “SINGH'; // Not valid
3. Boolean: Represents a true or false value.
let Flag = true;
let Flag = false;
6/7/2023 Prof. SHIV VEER SINGH 13
Data Types in JavaScript's…
4. Undefined: Represents a variable that has
been declared but not assigned a value.
let undefinedVar;
console.log(undefinedVar); // This will output
'undefined'
5. Null: Represents an intentional absence of
any object value.
let emptyValue = null;
6/7/2023 Prof. SHIV VEER SINGH 14
Data Types in JavaScript's…
6. Symbol (ES6): Represents a unique and
immutable value used as object property keys.
const uniqueID = Symbol('description');
7. BigInt (ES11): Represents large integers that
cannot be represented by the Number data
type.
const bigIntValue =
1234567891234567890345678901234567890n
6/7/2023 Prof. SHIV VEER SINGH 15
Data Types in JavaScript's…
8. Object: Represents complex data structures, including key-value
pairs.
let person = {
firstName: “SHIV",
lastName: “VEER",
age: 42,
};
9. Array: Represents a list of values.
let colors = ["red", "green", "blue"];

6/7/2023 Prof. SHIV VEER SINGH 16


Data Types in JavaScript's…
10. Function: Functions are objects in JavaScript and can be
assigned to variables, passed as arguments, and returned from
other functions.
function add(a, b)
{
return a + b;
}

11. Date: Represents dates and times.


let today = new Date();

6/7/2023 Prof. SHIV VEER SINGH 17


Data Types in JavaScript's…
12. RegExp: Represents regular expressions for
pattern matching.
let pattern = /a[bcd]+/g;
13. Map (ES6): Represents a collection of key-
value pairs where keys can be of any data type.
let fruitPrices = new Map();
fruitPrices.set("apple", 1.0);
fruitPrices.set("banana", 0.5);

6/7/2023 Prof. SHIV VEER SINGH 18


Data Types in JavaScript's…
14. Set (ES6): Represents a collection of unique
values.
let uniqueNumbers = new Set([1, 2, 3, 4, 2]);

6/7/2023 Prof. SHIV VEER SINGH 19


variables used in JavaScript
• In JavaScript, variables are used to store and manage data.
Variables can hold various data types, and they are a
fundamental part of JavaScript programming.
1. var (Function-Scoped): var was the original way to
declare variables in JavaScript, but it has some issues,
particularly with variable scoping. Variables declared with
var are function-scoped, which means they are only
accessible within the function in which they are declared.
If declared outside of any function, they become global
variables.
var x=10;
6/7/2023 Prof. SHIV VEER SINGH 20
variables used in JavaScript…
2. let (Block-Scoped): Introduced in ES6 let
provides block-level scope, making it safer and
more predictable than var. Variables declared
with let are only accessible within the block in
which they are declared.
let y = 20;

6/7/2023 Prof. SHIV VEER SINGH 21


variables used in JavaScript…
3. const (Block-Scoped, Immutable): Also introduced in
ES6, const is used for variables that should not be
reassigned after their initial value is assigned. Like let, it
is block-scoped.
const PI = 3.14159;
4. Global Variables: Variables declared outside of any
function or block become global variables. They are
accessible from anywhere in the code, which can lead to
unintended side effects and is generally discouraged.
globalVar = 100
6/7/2023 Prof. SHIV VEER SINGH 22
variables used in JavaScript…
5. Function Parameters: Function parameters act as variables that receive
values when the function is called. They are local to the function.
function add(a, b)
{
return a + b;
}
6. Object Properties: We can use variables as properties of objects. These
are often referred to as object properties or object fields.
const person = {
firstName: “SHIV",
lastName: “VEER",
};

6/7/2023 Prof. SHIV VEER SINGH 23


variables used in JavaScript…
7Array Elements: Arrays are a type of object in JavaScript,
and you can use variables to store elements within an array.
const arr = [10,20,30,40,50,60,];
const colors = ["red", "green", "blue"];
8. Dynamic Variables: JavaScript allows variables to change
data types during runtime. This flexibility is due to
JavaScript's dynamic typing. For example, you can reassign a
variable to a different type:
let myVar = 42;
myVar = "Hello, World!";

6/7/2023 Prof. SHIV VEER SINGH 24


variables used in JavaScript…
9. Function Declarations: In JavaScript, we can declare a
function as a variable. Function expressions can be assigned to
variables.
const multiply = function (a, b) {
return a * b;
};
10. Template Literals: In modern JavaScript, we can use
template literals to create string variables that can contain
variables or expressions within the string.
const name = “SHIV";
const greeting = `Hello, ${name}!`;
6/7/2023 Prof. SHIV VEER SINGH 25
Operators in JavaScript
Operators in JavaScript are symbols that allow
you to perform operations on variables and
values. JavaScript provides a wide range of
operators for various tasks, such as arithmetic,
assignment, comparison, and logical operations.

6/7/2023 Prof. SHIV VEER SINGH 26


Operators in JavaScript…
1. Arithmetic Operators: These operators are used for basic mathematical
operations.
+ (Addition), - (Subtraction), * (Multiplication)
/ (Division), % (Modulus, gives the remainder of a division), **
(Exponentiation)
let x = 10; let y = 5;
let sum = x + y;
let difference = x - y;
let product = x * y;
let quotient = x / y;
let remainder = x % y;
let power = x ** y;

6/7/2023 Prof. SHIV VEER SINGH 27


Operators in JavaScript…
2. Assignment Operators: These operators are
used to assign values to variables.
= (Assignment) let a = 5;
+= (Add and assign) let a += 3;
-= (Subtract and assign) let a -= 3;
*= (Multiply and assign) let a *= 3;
/= (Divide and assign) let a /= 3;
%= (Modulus and assign) let a %= 3;
6/7/2023 Prof. SHIV VEER SINGH 28
Operators in JavaScript…
3. Comparison Operators: These operators are used to compare
values and return a Boolean result.
== (Equal to)
!= (Not equal to)
=== (Strict equal to, also checks data type)
!== (Strict not equal to)
> (Greater than)
< (Less than)
>= (Greater than or equal to)
<= (Less than or equal to)

6/7/2023 Prof. SHIV VEER SINGH 29


Operators in JavaScript…
4. Logical Operators: These operators are used
to perform logical operations and return
Boolean values.
&& (Logical AND)
|| (Logical OR)
! (Logical NOT)

6/7/2023 Prof. SHIV VEER SINGH 30


Operators in JavaScript…
5. Ternary Operator (Conditional Operator):
This operator provides a concise way to write
conditional statements.
let age = 20; let canVote = age >= 18 ? "Yes" :
"No";

6/7/2023 Prof. SHIV VEER SINGH 31


Operators in JavaScript…
6. String Concatenation Operator: The +
operator can be used to concatenate strings.
let firstName = “SHIV"; let lastName = “VEER";
let fullName = firstName + " " + lastName;

6/7/2023 Prof. SHIV VEER SINGH 32


Conditional Statements used in Java Scripts
• In JavaScript, conditional statements are used
to make decisions in your code. These
statements allow you to execute different
blocks of code based on whether a certain
condition is true or false. There are several
conditional statements in JavaScript, including
if, if-else, if-else if-else…, and the switch
statement.
6/7/2023 Prof. SHIV VEER SINGH 33
Conditional Statements used in Java Scripts
• if Statement: The if statement is used to
execute a block of code if a specified condition
is true.
let num = 18;
if (num%2==0)
{
console.log(“Number is Even.");
}
6/7/2023 Prof. SHIV VEER SINGH 34
Conditional Statements used in Java Scripts
• if-else Statement: The if-else statement allows you to
execute one block of code if a condition is true and another
block if it is false.
let num = 18;
if (num%2==0)
{
console.log(“Number is Even.");
}
else {
console.log(" Number is odd.");
} 6/7/2023 Prof. SHIV VEER SINGH 35
Conditional Statements used in Java Scripts
• if-else if-else.. Statement: You can use if-else
if-else to handle multiple conditions in a
sequence.
• let score = 75;
• if (score >= 90)
• { console.log("You got an Grade A."); }
• else if (score >= 80) { console.log("You got a Grade B."); }
• else if (score >= 70) { console.log("You got a Grade C."); }
• else { console.log("You need to study harder."); }

6/7/2023 Prof. SHIV VEER SINGH 36


Conditional Statements used in Java Scripts
• switch Statement: The switch statement is used when you want to
compare a single value against multiple possible values and execute
different code blocks based on the match.
• let day = "Monday";
• switch (day)
• {
• case "Monday":
• console.log("It's the start of the workweek.");
• break;
• case "Friday":
• console.log("It's almost the weekend.");
• break;
• default:
• console.log("It's another day of the week.");
• }

6/7/2023 Prof. SHIV VEER SINGH 37


Conditional Statements used in Java Scripts
• Ternary Operator (Conditional Operator): The ternary
operator is a concise way to write simple conditional
statements in a single line.
let isSunny = true; let weatherMessage = isSunny ? "It's a sunny day" : "It's not
sunny today"; console.log(weatherMessage);

6/7/2023 Prof. SHIV VEER SINGH 38


Loops in Java Scripts
• JavaScript provides several types of loops that allow you to
execute a block of code repeatedly. These loops are essential for
iterating through arrays, processing data, and controlling the flow
of your programs. There are following types of loops used in java
Scripts:
• for loop
• while loop
• do...while loop
• for...in loop
• for...of loop
• forEach loop
• map loop
6/7/2023 Prof. SHIV VEER SINGH 39
Loops in Java Scripts…
• for loop
• The for loop is used when you know the number
of iterations in advance. It consists of three parts:
initialization, condition, and update. example that
prints numbers from 1 to 20:
for (let i = 1; i <= 20; i++)
{
console.log(i);
}
6/7/2023 Prof. SHIV VEER SINGH 40
Loops in Java Scripts…
Use break in for loop before condition is false

6/7/2023 Prof. SHIV VEER SINGH 41


Loops in Java Scripts…
while loop
The while loop repeats a block of code as long as a specified
condition is true. It is suitable for situations where you don't
know the exact number of iterations in advance. example
that prints numbers from 1 to 10 using a while loop:
let i = 1;
while (i <= 10)
{
console.log(i); i++;
}

6/7/2023 Prof. SHIV VEER SINGH 42


Loops in Java Scripts…
• do...while loop
• The do...while loop is similar to the while loop, but it
guarantees that the block of code is executed at least
once, as the condition is checked after the code block.
example:
let i = 1; do
{
console.log(i); i++;
}
while (i <= 15);
6/7/2023 Prof. SHIV VEER SINGH 43
Loops in Java Scripts…
• for...in loop
The for...in loop is used to iterate over the properties of an object. It's
often used with objects and is not recommended for arrays. example:
const stu =
{
a: “aman",
b: “shubham",
c: “yuvraj" };
for (let key in stu )
{ console.log(key + ": " + stus[key]);
}

6/7/2023 Prof. SHIV VEER SINGH 44


Loops in Java Scripts…
• for...of loop
The for...of loop is used to iterate over the values of iterable objects like
arrays, strings,set and maps. example with an array:

let numArray = [1, 4, 16, 25, 49]; Add elements in set

console.log("Elements of numArray are->");

// for...of Loop
for (let value of numArray) {
console.log(value);
}

6/7/2023 Prof. SHIV VEER SINGH 45


Loops in Java Scripts…
• A forEach loop is a method on arrays that
executes a function for each element in the
array.
const arr = [1, 2, 3];
arr.forEach(val => console.log(val));

6/7/2023 Prof. SHIV VEER SINGH 46


Loops in Java Scripts…
• A map loop is a method on arrays that creates
a new array by executing a function on each
element in the array.
const arr = [1, 2, 3];
const newArr = arr.map(val => val * 2);
console.log(newArr);

6/7/2023 Prof. SHIV VEER SINGH 47


JS Popup boxes
alert
 The alert() method in JavaScript is used to display a virtual alert box.
An alert box is used to display a message to the user. It only
provides an OK button to acknowledge the message.
 It is mostly used to give a warning message to the users.
 Syntex: alert("This is an alert dialog box!");

6/7/2023 Prof. SHIV VEER SINGH 48


JS Popup boxes(cont..)
Confirmation
 It is widely used for taking the opinion from the user on the specific option.
 A confirm box is used when you want the user to confirm or cancel an action. It
provides OK and Cancel buttons and can be used to gather a boolean response.
 var result = confirm("Do you want to proceed?");
 if (result)
 { // User clicked OK
 console.log("User wants to proceed."); }
 else { // User clicked Cancel console.log("User canceled the action."); }

6/7/2023 49
JS Popup boxes(cont..)
Prompt Dialog box
 The prompt dialog box is used when it is required to pop-up a text box for
getting the user input.
 It provides an input field where the user can enter a value. The entered
value is captured as a string.
var userInput = prompt("Please enter your name:", “SHIV VEER");
if (userInput !== null)
{ // User entered a value
console.log("Hello, " + userInput + "!"); }
else
{ // User clicked Cancel or closed the prompt
console.log("User canceled or did not enter a value."); }

6/7/2023 Prof. SHIV VEER SINGH 50


Java script Events

• The change in the state of an object is known as an Event.

• represents that some activity is performed by the user or by the


browser.

• When JavaScript code is included in HTML, js react over


these events and allow the execution.

• Java Script handles the HTML events via Event Handlers.


6/7/2023 Prof. SHIV VEER SINGH 51
Common HTML Events
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

6/7/2023 Prof. SHIV VEER SINGH 52


JavaScript Event Handlers
 Things that should be done every time a page loads

 Things that should be done when the page is closed

 Action that should be performed when a user clicks a button

 Content that should be verified when a user inputs data

 HTML event attributes can execute JavaScript code directly

 HTML event attributes can call JavaScript functions

 You can assign your own event handler functions to HTML elements

 You can prevent events from being sent or being handled


6/7/2023 Prof. SHIV VEER SINGH 53
• Event handlers are functions or pieces of code that are
executed in response to a specific event occurring in
the browser, such as a user clicking a button, moving
their mouse, or submitting a form.
• Event Handling: Event handling is the process of
defining how your web page or application should
respond to these events. This is where event handlers
come into play. Event handlers are functions or code
snippets that you define to specify what should
happen when a specific event occurs. When the event
occurs, the associated event handler is executed.
6/7/2023 Prof. SHIV VEER SINGH 54
Types of Event Handlers:
• Inline Event Handlers: We can directly define
event handlers in our HTML code using
attributes like onclick, onmouseover, or
onsubmit.
• Ex.
• <button onclick="myFunction()">Click me</button>

6/7/2023 Prof. SHIV VEER SINGH 55


• DOM Level 0 Event Handlers: We can set
event handlers in our JavaScript code by
assigning functions to properties of DOM
elements
• Ex.
• const button = document.getElementById('myButton');
button.onclick = myFunction;

6/7/2023 Prof. SHIV VEER SINGH 56


• DOM Level 2 Event Handlers: This approach
provides more control and flexibility. We can
use methods like addEventListener to attach
event listeners to elements.
• Ex.
• const button = document.getElementById('myButton');
button.addEventListener('click', myFunction);

6/7/2023 Prof. SHIV VEER SINGH 57


• Event Handler Functions: Event handler functions are
just regular JavaScript functions. They can take
parameters, and these parameters often include event
objects, which provide information about the event,
such as the target element, event type, and more.
Here's a simple example of an event handler function:
• function myFunction(event)
{
// Handle the event
}
6/7/2023 Prof. SHIV VEER SINGH 58
• Preventing Default Behavior: In many cases, you might want to
prevent the default behavior of an event, like preventing a form
from submitting or a link from navigating to a new page. You can
do this by calling event.preventDefault() within your event handler.
• Event Bubbling and Capturing: Events in the DOM propagate in
two phases: capturing and bubbling. Event handlers can be set to
listen in either phase. You can control the order of execution of
event handlers by specifying the phase when using
addEventListener.
• Event Delegation: Event delegation is a technique where you
attach a single event handler to a common ancestor of multiple
elements rather than attaching individual handlers to each
element. This is efficient and useful for elements added
dynamically to the DOM.
6/7/2023 Prof. SHIV VEER SINGH 59
JS Arrays

In JavaScript, an array is a data structure used


to store a collection of values. Arrays can hold
various data types, including numbers,
strings, objects, and even other arrays. Arrays
are ordered, indexed collections, and each
element in the array is associated with a
unique numeric index, starting from 0.

6/7/2023 Prof. SHIV VEER SINGH 60


Working with Arrays
Creating an Array: We can create an array using square
brackets [] or the Array constructor:
Ex.
let fruits = ['apple', 'banana', 'cherry'];
let numbers = new Array(1, 2, 3, 4, 5);
Accessing Array Elements: We can access array elements
using their index. Arrays are zero-based, so the first
element is at index 0.
console.log(fruits[0]);
console.log(numbers[2]);
6/7/2023 Prof. SHIV VEER SINGH 61
Working with Arrays

• Modifying Array Elements: We can change the


value of an element by assigning a new value to
a specific index.
• fruits[1] = 'grape';
• console.log(fruits);
Array Length: We can find the length of an array
using the length property.
let length = fruits.length;
console.log(length);
6/7/2023 Prof. SHIV VEER SINGH 62
Working with Arrays

• Adding and Removing Elements: We can add


elements to the end of an array using the
push method and remove elements from the
end using the pop method:
fruits.push('orange'); // Add 'orange' to the end
fruits.pop(); // Remove the last element
('orange')

6/7/2023 Prof. SHIV VEER SINGH 63


Working with Arrays

• Iterating Over Arrays: We can loop through


the elements of an array using for loops,
forEach, or other looping mechanisms.
for (let i = 0; i < fruits.length; i++)
{ console.log(fruits[i]); } //
Using forEach
fruits.forEach(function(fruit)
{ console.log(fruit); });
6/7/2023 Prof. SHIV VEER SINGH 64
Working with Arrays

• Slicing and Splicing Arrays: We can create a


new array by slicing an existing array or
insert/replace elements at a specific position
using the splice method.
let slicedArray = fruits.slice(1, 3); // Creates a new array with
elements from index 1 to 2
fruits.splice(1, 2, 'pear', 'grape'); // Replace two elements with
'pear' and 'grape' starting at index 1

6/7/2023 Prof. SHIV VEER SINGH 65


Working with Arrays

• Adding and Removing Elements at the


Beginning: We can add elements to the
beginning of an array using the unshift
method and remove elements from the
beginning using the shift method.
fruits.unshift('kiwi'); // Add 'kiwi' to the
beginning
fruits.shift();

6/7/2023 Prof. SHIV VEER SINGH 66


JavaScript Objects (JS Objects)

JavaScript objects are a fundamental data structure


that allows to group related data and functionality
into a single entity. Objects are composed of key-
value pairs, where the keys are strings (or symbols in
some cases), and the values can be any valid
JavaScript data type, including other objects. Objects
are used extensively in JavaScript for modeling real-
world entities and organizing data.

6/7/2023 Prof. SHIV VEER SINGH 67


JavaScript Objects

• Creating Objects:
• There are multiple ways to create objects in JavaScript.
The most common methods are:
1. Object Literal Syntax: This is the simplest way to
create an object. We define key-value pairs within curly
braces { }.
const person = {
firstName: “SHIV VEER", Name: “SINGH", age: 43,
isEmployed: true,
};6/7/2023 Prof. SHIV VEER SINGH 68
JavaScript Objects

2. Using the new keyword with Object


Constructor: We can use the new keyword to
create an object using the Object constructor.
const car = new Object();
car.make = "Toyota";
car.model = "Camry";
car.year = 2022;

6/7/2023 Prof. SHIV VEER SINGH 69


JavaScript Objects

3. Object.create(): This method allows to create


an object with a specified prototype object.
const animal = Object.create(null);
animal.type = "Dog";
animal.breed = "Golden Retriever";

6/7/2023 Prof. SHIV VEER SINGH 70


JavaScript Objects

• Accessing Object Properties:


We can access object properties using dot
notation or square brackets:
console.log(person.firstName);
console.log(car["make"]);

6/7/2023 Prof. SHIV VEER SINGH 71


JavaScript Objects

• Modifying Object Properties:


• We can modify object properties by assigning
new values:
person.age = 41;
car["make"] = "Honda";

6/7/2023 Prof. SHIV VEER SINGH 72


JavaScript Objects

• Adding and Deleting Object Properties:


• We can add new properties or delete existing
properties dynamically:
person.gender = "Male";
property delete car.year;

6/7/2023 Prof. SHIV VEER SINGH 73


JavaScript Objects

• Object Methods:
Objects can also contain functions, known as
methods:
const calculator = {
add: function (a, b) {
return a + b; },
subtract: function (a, b) {
return a - b; }, };
console.log(calculator.add(5, 3));
console.log(calculator.subtract(10, 4));
6/7/2023 Prof. SHIV VEER SINGH 74
JavaScript Objects

• Object Property Types:


• Object properties can contain any valid JavaScript
data type, including other objects.
const book = {
title: "The Catcher in the Rye",
author: {
firstName: "J.D.",
lastName: "Salinger", },
isPublished: true,
};
6/7/2023 Prof. SHIV VEER SINGH 75
JavaScript Objects

• Iterating Over Object Properties:


We can loop through an object's properties
using for...in loop:
for (let key in person)
{
console.log(key, person[key]);
}

6/7/2023 Prof. SHIV VEER SINGH 76


JavaScript Function Definitions
• Javascript functions are defined with function keyword
• You can use a function declaration or a function expression
Function Declarations
function functionName(parameters) {
// code to be executed
}
Declared functions are not executed immediately. They are "saved for later use", and will be executed
later, when they are invoked (called upon).
function myFunction(a, b) {
return a * b;
}
Function Expressions
A JavaScript function can also be defined using an expression
A function expression can be stored in a variable:
const x = function (a, b) {return a * b};

6/7/2023 Prof. SHIV VEER SINGH 77


Cont….
 After a function expression has been stored in a variable, the variable can be used
as a function:
const x = function (a, b) {return a * b};
let z = x(4, 3);
 The function above is actually an anonymous function (a function without a name).
 Functions stored in variables do not need function names. They are always invoked
(called) using the variable name.
The Function() Constructor
 Function can be defined with a built-in java script function constructor called
function()
const myFunction = new Function("a", "b", "return a
*b");

let x = myFunction(4, 3);

6/7/2023 Prof. SHIV VEER SINGH 78


Self-Invoking Functions

• Function expressions can be made "self-invoking".


• A self-invoking expression is invoked (started) automatically, without being called.
• Function expressions will execute automatically if the expression is followed by ().
• You cannot self-invoke a function declaration.
• we have to add parentheses around the function to indicate that it is a function
expression:
Example
(function () {
let x = "Hello!!"; // I will invoke myself
})();

• The function above is actually an anonymous self-invoking function (function


without name)

6/7/2023 Prof. SHIV VEER SINGH 79


Arrow Functions
Arrow functions allows a short syntax for writing function expressions.
Example :
// ES5
var x = function(x, y) {
return x * y;
}

// ES6
const x = (x, y) => x * y;
 Arrow functions do not have their own this. They are not well suited for defining object
methods
 Arrow functions are not hoisted. They must be defined before they are used
 Using const is safer than using var, because a function expression is always constant
value.
 You can only omit the return keyword and the curly brackets if the function is a single
statement. Because of this, it might be a good habit to always keep them:
Example
const x = (x, y) => { return x * y };
6/7/2023 Prof. SHIV VEER SINGH 80
JavaScript Function Parameters
A JavaScript function does not perform any checking on parameter values (arguments).
function functionName(parameter1, parameter2, parameter3) {
// code to be executed
}
Function parameters are the names listed in the function definition.
Function arguments are the real values passed to (and received by) the function
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.
Default Parameters
• If a function is called with missing arguments (less than declared), the missing values
are set to undefined
function myFunction(x, y) {
if (y === undefined) {
y = 2;
6/7/2023 Prof. SHIV }
VEER SINGH 81
}
Form Validation Example
• <!DOCTYPE html>
• <html>
• <head>
• <title>Form Validation Example</title>
• <style>
• .error {
• color: red;
• }
• </style>
• </head>
6/7/2023 Prof. SHIV VEER SINGH 82
Form Validation Example Cont..
• <body>
• <h1>Form Validation Example</h1>
• <form id="myForm">
• <label for="name">Name:</label>
• <input type="text" id="name" name="name"><span id="nameError"
class="error"></span><br>

• <label for="email">Email:</label>
• <input type="text" id="email" name="email"><span id="emailError"
class="error"></span><br>

• <label for="password">Password:</label>
• <input type="password" id="password" name="password"><span id="passwordError"
class="error"></span><br>

• <input type="submit" value="Submit">

6/7/2023 Prof. SHIV VEER SINGH 83


Form Validation Example Cont..
• </form>

• <script>
• const form = document.getElementById("myForm");
• const nameInput = document.getElementById("name");
• const emailInput = document.getElementById("email");
• const passwordInput = document.getElementById("password");
• const nameError = document.getElementById("nameError");
• const emailError = document.getElementById("emailError");
• const passwordError = document.getElementById("passwordError");

• form.addEventListener("submit", function (event) {


• let isValid = true;
6/7/2023 Prof. SHIV VEER SINGH 84
Form Validation Example Cont..
• // Name validation
• if (nameInput.value.trim() === "") {
• nameError.textContent = "Name is
required.";
• isValid = false;
• } else {
• nameError.textContent = "";
• }
6/7/2023 Prof. SHIV VEER SINGH 85
Form Validation Example Cont..
• // Email validation
• const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-
Z0-9.-]+\.[a-zA-Z]{2,4}$/;
• if (!emailPattern.test(emailInput.value)) {
• emailError.textContent = "Invalid email
address.";
• isValid = false;
• } else {
• emailError.textContent = "";
• }
6/7/2023 Prof. SHIV VEER SINGH 86
Form Validation Example Cont..
• // Password validation
• if (passwordInput.value.length < 6) {
• passwordError.textContent =
"Password must be at least 6 characters long.";
• isValid = false;
• } else {
• passwordError.textContent = "";
• }
6/7/2023 Prof. SHIV VEER SINGH 87
Form Validation Example Cont..
• if (!isValid) {
• event.preventDefault(); // Prevent
form submission if there are errors
• }
• });
• </script>
• </body>
• </html>
6/7/2023 Prof. SHIV VEER SINGH 88
Example of Constructor

class Person {
constructor() {
console.log("Constructor is called")
}
}
let p1= new Person() //contructor is called

let p2= new Person() //contructor is called

6/7/2023 Prof. SHIV VEER SINGH 89


Parameters to the Constructor method
Constructors are just like normal functions in the way that they
also accept parameters.
We need to pass parameter values when we create a new class
instance.
Example:

class Person {
firstName:string;
lastName:string;
constructor(fName:string, lName:string) {
this.firstName=fName;
this.lastName=lName;
}
}

6/7/2023 Prof. SHIV VEER SINGH 90


Strict Equality (==) Loose Equality (===) in Typescript
• The Typescript has two operators for checking
equality.
• One is == (equality operator or loose equality
operator) and the other one is === (strict equality
operator).
• Both of these operators check the value of operands
for equality.
• But, the difference between == & === is that the ==
does a type conversion before checking for equality.

6/7/2023 Prof. SHIV VEER SINGH 91


Checking Equality
Two values are equal if they are
 identical strings
 numerically equivalent numbers
 identical Boolean values
 the same object (reference types)
Example:
let a=10
let b=10
console.log(a==b) //true
console.log(a===b) //true
6/7/2023 Prof. SHIV VEER SINGH 92
Difference between == & ===

• If types are same then there is no difference


between == & ===
• If types are different then == does a type
conversion.
• It will attempt to convert them to a string,
number, or boolean. before doing the
comparison.
• === returns false.
6/7/2023 Prof. SHIV VEER SINGH 93
Equality Operator ==
let a=10
let b=10
console.log(a==b) //true
But, in the following code, the variable b is a string and not a number.
The Typescript makes the type conversion of b from string to number and then does the
comparison. Hence the result is true again.
let a=10
let b="10"
console.log(a==b) //true

let a="01"
let b=1
console.log(a==b);//true

6/7/2023 Prof. SHIV VEER SINGH 94


Strict Equality Operator ===

• The strict Equality operator, returns false if the types are


different.
let a=10
let b=10
console.log(a===b) //true
let a=10
let b="10“
console.log(a===b) //false

6/7/2023 Prof. SHIV VEER SINGH 95


Thank You

6/7/2023 Prof. SHIV VEER SINGH 96

You might also like