0% found this document useful (0 votes)
17 views68 pages

WT Unit - Iii

Uploaded by

pradeepkumar.mca
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)
17 views68 pages

WT Unit - Iii

Uploaded by

pradeepkumar.mca
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/ 68

Unit – III

ADVANCED JAVASCRIPT

Regular Expression- Events - OOPs- Inheritance and


Prototype Chain - Memory Management- Promises -
Iterators and generators - Validations - Exception
Handling - Global Objects -JS this Keyword - Strict Mode -
setTimeOut() and setInterval() Method - typeOf Operator -
Debugging - Local Storage - Callback - Closures - JS
defer- scope - Void. JavaScript DOM Manipulation:
Manipulating the DOM with JavaScript - Handling events
and user interactions with JavaScript- Debugging and
troubleshooting JavaScript code.
JavaScript RegExp(Regular Expression)
A regular expression is a character sequence defining a search pattern.
 It’s employed in text searches and replacements, describing what to search for within
a text.
 Ranging from single characters to complex patterns, regular expressions enable
various text operations with versatility and precision.
Syntax:
/pattern/modifiers;
Regular Expression Modifiers can be used to perform
multiline searches which can also be set to case-insensitive
matching:
Expressions Descriptions
g Find the character globally

i Find a character with case-insensitive matching

m Find multiline matching


Regular Expression Brackets can Find characters in a
specified range

Expressions Description

[abc] Find any of the characters inside the brackets

[^abc] Find any character, not inside the brackets

[0-9] Find any of the digits between the brackets 0 to 9

[^0-9] Find any digit not in between the brackets

(x | y) Find any of the alternatives between x or y separated with |


Regular Expression Meta characters are characters with a
special meaning:
Metac Find a match that is not present at
haract Description \B
the beginning or end of a word.
er
\0 Find the NULL character.
Search single characters, except line
\.
terminator or newline. \n Find the newline character.
Find the word character i.e. \f Find the form feed character
\w
characters from a to z, A to Z, 0 to 9
\r Find the carriage return character
\d Find a digit
\t Find the tab character
Search non-digit characters i.e all the
\D \v Find the vertical tab character
characters except digits
\s Find a whitespace character Find the Unicode character specified
\uxxxx
by the hexadecimal number xxxxx
\S Find the non-whitespace characters.
Find a match at the beginning or at
\b
the end of a word
Regular Expression Quantifiers are used to define
quantities occurrence
Quantifier Description

n+ Match any string that contains at least one n

n* Match any string that contains zero or more occurrences of n

n? Match any string that contains zero or one occurrence of n

m{X} Find the match of any string that contains a sequence of m, X times

m{X, Y} Find the match of any string that contains a sequence of m, X to Y times

Find the match of any string that contains a sequence of m, at least X


m{X,}
times

m$ Find the match of any string which contains m at the end of it

^m Find the match of any string which contains m at the beginning of it


Regular Expression Object Properties:
Property Description
Return the function that created the RegExp object’s
constructor
prototype

global Specify whether the “g” modifier is set or not

ignorecase Specify whether the “i” modifier is set or not

lastindex Specify the index at which to start the next match

multiline Specify whether the “m” modifier is set or not

source Return the text of RegExp pattern


Regular Expression Object Methods:

Method Description
Used to compile the regular expression while executing of
compile()
script

exec() Used to test for the match in a string.

test() Used to test for a match in a string

toString() Return the string value of the regular expression


Example:
function GFGFun() {
let str = "Department of Computer Applications";
let n = str.search(/Computer Applications/i);
console.log(n);
}
GFGFun();

Output : 14
Using String Methods

In JavaScript, regular expressions are often used with the two
string methods: search() and replace().
The search() method uses an expression to search for a
match and returns the position of the match.
The replace() method returns a modified string where the
pattern is replaced.
Using String search() With a Regular Expression
function myFunction() { Output:
6
// input string
let str = "Visit Hindusthan!"; -1

// searching string with modifier i


let n = str.search(/Hindusthan/i);

console.log(n);

// searching string without modifier i


let m = str.search(/hindusthan/);

console.log(m);
}
Use String replace() With a Regular Expression
function myFunction() {
Output:
// input string Please visit
let str = "Please visit hicet!"; Hindusthan!

// replacing with modifier i


let txt = str.replace(/hicet/i, "Hindusthan");

console.log(txt);
}
myFunction();
JavaScript Events
JavaScript Events are actions or occurrences that happen
in the browser.
They can be triggered by various user interactions or by the
browser itself.
Common events include mouse clicks, keyboard presses, page
loads, and form submissions.
Event handlers are JavaScript functions that respond to these
events, allowing developers to create interactive web
applications.
<HTML-element Event-Type = "Action to be performed">
Syntax:
Mouse events:
Event Performed Event Handler Description

click onclick When mouse click on an element

mouseover onmouseover When the cursor of the mouse comes over the element

mouseout onmouseout When the cursor of the mouse leaves an element

mousedown onmousedown When the mouse button is pressed over the element

mouseup onmouseup When the mouse button is released over the element

mousemove onmousemove When the mouse movement takes place.


Keyboard events:

Event Performed Event Handler Description

When the user press


Keydown & Keyup onkeydown & onkeyup and then release the
key
Form events:
Event Event Handler Description
Performed

focus onfocus When the user focuses on an element

submit onsubmit When the user submits the form

blur onblur When the focus is away from a form element

When the user modifies or changes the value of a


change onchange
form element
Window/Document events
Event Performed Event Handler Description

load onload When the browser finishes the loading of the page

When the visitor leaves the current webpage, the


unload onunload
browser unloads it

resize onresize When the visitor resizes the window of the browser
<!doctype html>
<html>

<head>
<script>
function hiThere() {
alert('Hi there!');
}
</script>
</head>

<body>
<button type="button"
onclick="hiThere()"
style="margin-left: 50%;">
Click me event
</button>
</body>

</html>
<!doctype html>
<html>

<head>
<script>
let a=0;
let b=0;
let c=0;
function changeBackground() {
let x=document.getElementById('bg');
x.style.backgroundColor='rgb('+a+', '+b+', '+c+')';
a+=100;
b+=a+50;
c+=b+70;
if(a>255) a=a-b;
if(b>255) b=a;
if(c>255) c=b;
}
</script>
</head>

<body>
<h4>The input box will change color when UP arrow key is pressed</h4>
<input id="bg" onkeyup="changeBackground()" placeholder="write something"
style="color:#fff">
</body>
Object Oriented Programming in JavaScript

OOPs Concept in JavaScript

Object Classes Encapsulation

Abstraction Inheritance Polymorphism


Object
An Object is a unique entity that
contains properties and methods.
For example “a car” is a real-life Object, which has some
characteristics like color, type, model and performs certain actions
like driving.
The characteristics of an Object are called Properties in Object-
Oriented Programming and the actions are called methods.
 An Object is an instance of a class.
Objects are everywhere in JavaScript, almost every element is an
Object whether it is a function, array, or string.
A Method in javascript is a property of an object whose value is a
function.
The object can be created in two ways in JavaScript:
• Object Literal
• Object Constructor
Object Literal
// Defining object
let person = { Output
first_name: 'pradeep',
The name of the person
last_name: 'kumar',
is pradeep kumar
//method
123456789
getFunction: function () {
return (`The name of the person is
${person.first_name} ${person.last_name}`)
},
//object within object
phone_number: {
mobile: '123456789',
landline: '224466'
}
}
console.log(person.getFunction());
console.log(person.phone_number.mobile);
Object Constructor
Output:
// Using a constructor Mukul
function person(first_name, last_name) { Rahul anand
this.first_name = first_name;
this.last_name = last_name;
}
// Creating new instances of person object
let person1 = new person('Mukul', 'anand');
let person2 = new person('Rahul', 'kumar');

console.log(person1.first_name);
console.log(`${person2.first_name} $
{person1.last_name}`);
Classes
Classes are blueprints of an Object.
 A class can have many Objects because the class is
a template while Objects are instances of the class or the
concrete implementation.
// Defining class using es6
class Vehicle {
constructor(name, maker, engine) {
this.name = name;
this.maker = maker;
this.engine = engine;
}
getDetails() {
return (`The name of the bike is ${this.name}.`)
}
}
// Making object with the help of the constructor
let bike1 = new Vehicle('Hayabusa', 'Suzuki', '1340cc');
let bike2 = new Vehicle('Ninja', 'Kawasaki', '998cc');

console.log(bike1.name); // Hayabusa
console.log(bike2.maker); // Kawasaki
console.log(bike1.getDetails());
Polymorphism
Polymorphism is one of the core concepts of object-oriented
programming languages.
Polymorphism means the same function with different
signatures is called many times.
In real life, for example, a boy at the same time may be a
student, a class monitor, etc.
 So a boy can perform different operations at the same time.
Polymorphism can be achieved by method overriding and
method overloading
Features of Polymorphism:
Programmers can use the same method name repeatedly.
Polymorphism has the effect of reducing the number of
functionalities that can be paired together.
Example:
class A {
area(x, y) {
console.log(x * y);
}
Output:
} 20000
class B extends A { Class B
area(a, b) {
super.area(a, b);
console.log('Class B')
}
}
let ob = new B();
let output = ob.area(100, 200);
Encapsulation
The JavaScript Encapsulation is a process of binding the data
(i.e. variables) with the functions acting on that data.
 It allows us to control the data and validate it. To achieve an
encapsulation in JavaScript: -
Use var keyword to make data members private.
Use setter methods to set the data and getter methods to get
that data.

The encapsulation allows us to handle an object using the


following properties:
Read/Write - Here, we use setter methods to write the data and
getter methods read that data.
Read Only - In this case, we use getter methods only.
Benefits of encapsulation in JavaScript:
Data Security: Encapsulation helps in protecting the data by
preventing direct access to private variables. This ensures
that the data is not modified inappropriately.
Code Reusability: Encapsulation makes it easier to reuse
code since objects are self-contained and can be used in
different parts of the application.
Maintenance: Encapsulation makes it easier to maintain the
code since objects are independent of each other and changes
made to one object do not affect the others.
Example:
class BankAccount {
constructor(accountNumber, withdraw(amount) {
accountHolderName, balance) { if (this._balance >= amount) {
this._accountNumber = accountNumber; this._balance -= amount;
this._accountHolderName = this.showAccountDetails();
accountHolderName; } else {
this._balance = balance; console.log("Insufficient
} Balance");
showAccountDetails() { }
console.log(`Account Number: $ }
{this._accountNumber}`); }
console.log(`Account Holder Name: $
{this._accountHolderName}`); let myBankAccount = new
console.log(`Balance: $ BankAccount("123456", "John Doe", 1000);
{this._balance}`); myBankAccount.deposit(500);
}
deposit(amount) {
this._balance += amount; Output: Account Number: 123456
this.showAccountDetails(); Account Holder Name: John Doe
} Balance: 150
ABSTRACTION
In JavaScript, abstraction refers to the concept of hiding
complex details and showing only an object's essential features
or functionalities.
Simply, it helps us reduce complexity and allows us to design
efficiently and implement complex software systems.
We can achieve abstraction with either abstract classes or with
the help of interfaces
An abstraction is a way of hiding the implementation details and
showing only the functionality to the users.
In other words, it ignores the irrelevant details and shows only
the required ones.
// Creating a constructor function
// for the abstract class Shape
function Shape() {
this.shapeName = &quot;shapeName&quot;;
throw new Error(`You cannot create an
instance of Abstract Class`);
}

Shape.prototype.display = function () {
return &quot;Shape is: &quot; + this.shapeName;
};

// Creating a constructor function


// for the concrete class Triangle
function Triangle(shapeName) {
this.shapeName = shapeName;
}

// Creating an object without


// using the function constructor
Triangle.prototype = Object
.create(Shape.prototype);

// Creating an instance of the Triangle class


let triangle = new Triangle(&quot;Equilateral&quot;);
Inheritance
JavaScript inheritance is the method through which the
objects inherit the properties and the methods from the other
objects.
 It enables code reuse and structuring of relationships between
objects, creating a hierarchy where a child object can access
features of its parent object.
Inheritance in JavaScript can be achieved in the following ways:

Table of Content
Prototypal Inheritance
Classical Inheritance
Functional Inheritance
Prototypal Inheritance
Objects inherit from other objects through their prototypes.
Each object has a prototype, properties, and methods
inherited from that prototype.
function Animal(name) {
this.name = name;
}

Animal.prototype.sound = function() {
console.log(&quot;Some generic sound&quot;);
};

function Dog(name, breed) {


Animal.call(this, name);
this.breed = breed;
}

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

Dog.prototype.sound = function() {
console.log(&quot;Woof! Woof!&quot;);
};

const myDog = new Dog(&quot;Buddy&quot;, &quot;Labrador&quot;);


myDog.sound();
Classical Inheritance
Introduced in ECMAScript6 (ES6)with the class keyword.
Uses a class-based approach similar to other programming
languages like Java or C++
class automobile {
constructor(name, cc) {
this.name = name;
this.cc = cc;
}
engine() {
console.log(`${this.name}
has ${this.cc} engine`);
}
}

class car extends automobile {


engine() {
console.log(this.name,
&quot;has &quot;, this.cc, &quot;cc engine&quot;);
}
}

let carz = new car('Rex', &quot;1149&quot;);


carz.engine();
Functional Inheritance
Objects inherit properties and methods from other objects
through function constructors.
 It uses functions to create objects and establish relationships
between them.
function Animal(name) {
const obj = {};
obj.name = name;

obj.sound = function() {
console.log(&quot;Some generic sound&quot;);
};

return obj;
}

function Dog(name, breed) {


const obj = Animal(name);
obj.breed = breed;

obj.sound = function() {
console.log(&quot;Woof! Woof!&quot;);
};

return obj;
}

const myDog = Dog(&quot;Buddy&quot;, &quot;Labrador&quot;);


myDog.sound(); // Outputs: Woof! Woof!
Memory Management in JavaScript
Memory management in JavaScript is handled automatically
by the runtime environment, typically the JavaScript engine in
web browsers or Node.js.
JavaScript uses a garbage collector to manage memory and
ensure that developers do not need to manually allocate or
deallocate memory.
Memory Life Cycle
Irrespective of the programming language, the memory life
cycle follows the following stages:

Allocates the memory we need: JavaScript allocates


memory to the object created.
Use the allocated memory.
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 stages are 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.
Difference between stack and Heap
Stack Heap

Primitive data types and


Objects and functions
references

Size is known at compile time Size is known at run time

Fixed memory allocated No limit for object memory


const employee = {
name: 'Rajesh',
age: 30,
};

const name="Ram"
// Allocates memory for object in heap.Values
// in object are primitive,which is why they
// are stored in stack.

function getname(name) {
return name;
}
// The function return value is given to stack after
// being evaluated in the heap

const newEmployee = employee;


// The newEmployee object will be stored in the stack and
Garbage Collection

Garbage collectors are used in releasing memory.


Once the engine recognizes that a variable, object, or
function is not needed anymore, it releases the memory it
occupied.
The main issue here is that it is very difficult to predict
accurately whether a particular variable, object, or function is
needed anymore or not.
Some algorithms help to find the moment when they become
obsolete with great precision.
Promise
A promise in JavaScript is like a container for a future value.
It is a way of saying, “I don’t have this value right now, but I
will have it later.” Imagine you order a book online. You don’t
get the book right away, but the store promises to send it to
you. While you wait, you can do other things, and when the
book arrives, you can read it.
In the same way, a promise lets you keep working with your
code while waiting for something else to finish, like loading
data from a server. When the data is ready, the promise will
deliver it.
How Does a Promise Work?
A promise can be in one of three states:

Pending: The promise is waiting for something to finish. For


example, waiting for data to load from a website.
Fulfilled: The promise has been completed successfully. The
data you were waiting for is now available.
Rejected: The promise has failed. Maybe there was a
problem, like the server not responding.
Syntax
let promise = new Promise(function(resolve, reject){
 //do something
});

Parameters

The promise constructor takes only one argument which is a callback


function
The callback function takes two arguments, resolve and reject
Perform operations inside the callback function and if everything went well
then call resolve.
If desired operations do not go well then call reject.
Creating a Promise
let myPromise = new Promise(function(resolve, reject) {
// some code that takes time, like loading data
let success = true; // change this to false to check error

if (success) {
resolve("The data has loaded successfully!");
} else {
reject("There was an error loading the data.");
}
});
Iterator
 Javascript Iterator is an object or pattern that allows us to traverse over a list or
collection.
 Iterators define the sequences and implement the iterator protocol that returns
an object by using a next() method that contains the value and is done.
 The value contains the next value of the iterator sequence and the done is the
boolean value true or false if the last value of the sequence has been consumed
then it’s true else false.
 We can check if any entity is by default iterable or not We can check its
prototype and can see if it is having a method Symbol(Symbol.iterator) or not.
 In Array.prototype you will find Symbol(Symbol.iterator): ƒ values() method. The
array is by default iterable. Also, String, Map & Set are built-in iterables
because their prototype objects all have a Symbol.iterator() method.
<script> Output:
const array = ['a', 'b', 'c'];

const it = array[Symbol.iterator](); {"value":"a","done":false}


// and on this iterator method we have ‘next’ method {"value":"b","done":false}
{"value":"c","done":false}
console.log(JSON.stringify(it.next()));
//{ value: "a", done: false }
{"done":true}

console.log(JSON.stringify(it.next()));
//{ value: "b", done: false }

console.log(JSON.stringify(it.next()));
//{ value: "c", done: false }

console.log(JSON.stringify(it.next()));
/* Actual it.next() will be { value: undefined,
done: true } but here you will get
{done: true} output because of JSON.stringify
as it omits undefined values*/
</script>
JavaScript Function Generator
A generator function uses the yield keyword to generate
values, pausing execution and sending values to the caller.
It retains the state to resume execution after yield, continuing
immediately after the last yield run.

Syntax :
// An example of generator function
function* gen(){
yield 1;
yield 2;
...
...
}
E.g Output:
// Generate Function generates three10
// different numbers in three calls 20
30
function* fun() {
yield 10;
yield 20;
yield 30;
}

// Calling the Generate Function


let gen = fun();
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
JavaScript Form Validation
JavaScript Form Validation is a way to ensure that the data
users enter into a form is correct before it gets submitted.
This helps ensure that things like emails, passwords, and
other important details are entered properly, making the user
experience smoother and the data more accurate.
Steps for Form Validation in JavaScript
 Data Retrieval:
 The first step is to get the user’s values entered into the form fields (like name,
email, password, etc.). This is done using document.forms.RegForm, which
refers to the form with the name “RegForm”.
 Data Validation:
 Name Validation: We check to make sure the name field isn’t empty and doesn’t
contain any numbers.
 Address Validation: We check that the address field isn’t empty.
 Email Validation: We make sure that the email field isn’t empty and that it
includes the “@” symbol.
 Password Validation: We ensure that the password field isn’t empty and that the
password is at least 6 characters long.
 Course Selection Validation: We check that a course has been selected from a
dropdown list.
Error Handling:
If any of the checks fail, an alert message is shown to the user
using window.alert, telling them what’s wrong.
The form focuses on the field that needs attention, helping
the user easily fix the error.
Submission Control:
If all the validation checks pass, the function returns true,
meaning the form can be submitted. If not, it returns false,
stopping the form from being submitted.
Focus Adjustment:
The form automatically focuses on the first field that has an
error, guiding the user to fix it.
Types of Form Validation
Client-side Validation:
This is done in the user’s browser before the form is
submitted. It provides quick feedback to the user, helping
them fix errors without sending data to the server first.
Server-side Validation:
Even though client-side validation is useful, it’s important
to check the data again on the server. This ensures that
the data is correct, even if someone tries to bypass the
validation in the browser.
Exception Handling in JavaScript
An exception signifies the presence of an abnormal condition
which requires special operable techniques.
In programming terms, an exception is the anomalous code
that breaks the normal flow of the code.
 Such exceptions require specialized programming constructs
for its execution.
Global object
The JavaScript global object allows you to access the variables,
functions, objects, etc., defined in the global scope and
available everywhere in the code.

In the browser, a global object is named as 'window', and in


Node.js, the global object is named 'global'. However, the
global object could have different names in different run-time
environments.

The 'globalThis' has been introduced in ECMAScript 2020,


which works with most browsers and run time environments as
a global object.
Syntax
var a = 10;
let b = window.a; // Accessing the global variable in the
browser

In the above syntax, variable 'a' is a global variable, as it is


defined in the global scope using the var keyword.
e.g
<html>
<body>
<div id = "output">The company name is: </div>
<script>
var name = "Tutorialspoint";
let company = window.name;
document.getElementById("output").innerHTML += company;
</script>
</body>
</html>

Output: The company name is: Tutorialspoint


JavaScript this Keyword
In JavaScript, this keyword refers to the object that is
currently executing a function or method.
Its value is determined by how a function is called. this
typically represents the context in which a function operates,
allowing access to the properties and methods of its
containing object.
The this keyword refers to different objects depending on
how it is used

When used within a method of an object, this points to that


object.
When used by itself, this points to the global object.
Within a function, this typically points to the global object.
In a function under strict mode, this becomes undefined.
During an event, this points to the element that triggered the
event.
Methods such as call(), apply(), and bind() can reassign this
to any desired object.
E.g Output
const person = {
Hello, my name is John and I am 30
name: 'John',
age: 30, years old.
greet() {
console.log('Hello, my name is ' +
this.name + ' and I am '
+ this.age +
' years old.');
}
};

person.greet();
JavaScript Strict Mode
 “use strict” is the literal expression that enables strict mode for JavaScript.
 It is added at the top of a JavaScript file, function, or block, and tells the
JavaScript engine to run the code in strict mode.
 In other words, this mode brings in a stricter set of rules for writing
JavaScript with more warnings and throwing more errors.
 Syntax:
"use strict";
console.log("Strict mode is enabled");

function myFunction() {
"use strict";
let x = 3.14;
console.log(x);
}
Window setTimeout()

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy