WT Unit - Iii
WT Unit - Iii
ADVANCED JAVASCRIPT
Expressions Description
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
Method Description
Used to compile the regular expression while executing of
compile()
script
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
console.log(n);
console.log(m);
}
Use String replace() With a Regular Expression
function myFunction() {
Output:
// input string Please visit
let str = "Please visit hicet!"; 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
mouseover onmouseover When the cursor of the mouse comes over the element
mousedown onmousedown When the mouse button is pressed over the element
mouseup onmouseup When the mouse button is released over the element
load onload When the browser finishes the loading of the page
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
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.
Shape.prototype.display = function () {
return "Shape is: " + this.shapeName;
};
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("Some generic sound");
};
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.sound = function() {
console.log("Woof! Woof!");
};
obj.sound = function() {
console.log("Some generic sound");
};
return obj;
}
obj.sound = function() {
console.log("Woof! Woof!");
};
return obj;
}
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
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
Parameters
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'];
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;
}
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()