AJS - 17th Dec
AJS - 17th Dec
AJS - 17th Dec
Lectures - 1 & 2
Inheritance:
Classical 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, we use the extends
keyword.
Exercise:
1. Create a class "Person" with a property "name".
2. Create a method "greet()" in the class that prints "Hello {name}".
3. Create a child class "Student" that inherits all methods and properties of the
"Person" class.
4. Create an object of the "Student" class and call the "greet()" method of
"Person" class.
The super keyword used inside a child class denotes its parent class.
As a function
As an object
Syntax:
super(arguments);
super.parentMethod(arguments);
Arguments: “This” keyword can accept all the arguments that have been used to
create a constructor.
Exercise:
1. Create a constructor of "Student" class that calls the constructor of "Person"
class using super.
Neither the base (parent) nor derived (child) class requires a constructor, nor
does the child class require a super() call. If you omit either constructor, an
assumed one is present.
If you do not call super(), you only get into trouble if you access "this" in some
manner.
First, you can avoid accessing this by explicitly returning an object from the
derived class constructor.
However, this is not what you want, because the object created via new B() does
not inherit A’s methods.
// Base class
class A {
constructor() {}
}
// Derived class
class B extends A {
constructor() {
// No super-constructor call here!
// Base class
class A {
constructor() {}
}
// Derived class
class B extends A {
constructor(...args) {
super(...args);
}
}
If a child class has the same method or property name as that of the parent
class, it will use the method and property of the child class. This concept is called
method overriding.
Exercise:
1. Add a new property "occupation" in the "Person" class and assign the value
"unemployed" to it.
2. Override "occupation" in the "Student" class with value "student".
3. Override the "greet()" method of "Person" class in "Student" class to print:
Hello student {name}.
occupation: {occupation}
Advantages of Inheritance:
1. Since a child class can inherit all the functionalities of the parent class, this
allows code reusability.
2. Once a functionality is developed, you can simply inherit it. No need to
reinvent the wheel. This allows cleaner and easily maintainable code.
3. Since you can also add your own functionalities in the child class, you can
inherit only the useful functionalities and define other required features.
// parent class
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello ${this.name}`); //Template Literals
}
}
//derived class
class Student extends Person {
}
// parent class
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello ${this.name}`); //Template Literals
}
}
//derived class
class Student extends Person {
constructor(name) {
console.log("Creating student class");
super(name);
}
}
class Person {
constructor(name) {
this.name = name;
this.occupation = "unemployed";
}
greet() {
console.log(`Hello ${this.name}`);
}
greetAgain() {
console.log(`Hello Again ${this.name}`);
}
}
student1.greet();
student1.greetAgain();
student1.greetInTheMorning();
student1.callParentGreet();
Prototypes:
JavaScript Prototype:
Pre-requisites:
1. Javascript Objects
2. Javascript Constructor Functions
const object_name = {
key1: value1, //---> properties
key2: value2
}
JavaScript Prototype: every function and object has its own hidden, internal
property, [[Prototype]]. We can access that [[Prototype]] using the __proto__
property.
Prototype Chaining: If an object tries to access the same property that is in the
constructor function and the prototype object, the object takes the property from
the constructor function.
Javascript Object:
const student = {
firstName: 'Swati',
age: 20,
greet: function() {
console.log('hello');
}
}
console.log(typeof student);
console.log(student.firstName);
console.log(student["firstName"]);
student.greet();
const student1 = {
firstName: 'Swati',
age: 20,
marks: {
science: 50,
math: 50
}
}
console.log(student1.marks);
console.log(student1.marks.science);
const person1 = {
name1: 'Swati'
}
person1.age = 20;
console.log(person1);
console.log(person2);
let person = {
name1: 'Swati'
}
console.log(person.name1);
let student = person;
student.name1 = 'Avni';
console.log(person.name1);
student.age = 20;
console.log(person);
console.log(person1.name);
console.log(person2.name);
person1.greet();
console.log(typeof Person);
function Person() {
this.name = 'Swati'
}
person1.age = 20;
console.log(person1);
console.log(person2);
console.log(person1.name);
console.log(person2.name);
person1.greet();
person2.greet();
function Person() {
this.name = 'Swati',
this.age = 20
}
person1.gender = 'female';
person1.greet = function() {
console.log('hello');
}
console.log(person1);
person1.greet(); //hello
//person2.greet(); //error
function Person () {
this.name = 'Swati',
this.age = 23
}
function Person () {
this.name = 'Swati',
this.age = 23
}
Person.prototype.gender = 'female';
Person.prototype.greet = function() {
console.log(`hello ${this.name}`);
}
// console.log(Person.prototype);
// console.log(person1.gender);
// console.log(person2.gender);
// console.log(Person.gender);
console.log(person1.gender);
console.log(person1.__proto__ === Person.prototype);
person1.greet();
person2.greet();
let user = {
showAccess: true
};
let premiumUser = {
ads: false
};
premiumUser.__proto__ = user;
console.log(premiumUser);
console.log(premiumUser.showAccess);
Overriding Prototype:
function Person () {
this.name = 'Swati',
this.age = 23
}
Person.prototype.gender = 'female';
let person1 = new Person();
Person.prototype = { class: 8 };
let person2 = new Person();
console.log(person1.gender); //female
console.log(person2.class); //8
function Person () {
this.name = 'Swati'
}
Person.prototype.age = 22;
let person1 = new Person();
console.log(person1.age);
//person1 -> Person -> JS Object -> null
console.log(person1.__proto__.__proto__.__proto__);
//Person -> JS Function -> JS Object -> null
console.log(Person.__proto__.__proto__.__proto__);
Property Descriptor:
When we create a JavaScript object, whether using object literal syntax or some other
means and add some properties to it, each property (key) gets a default property descriptor.
A property descriptor is a simple JavaScript object associated with each property of the
object that contains information about that property such as its value and other meta-data.
Object.getOwnPropertyDescriptor(obj, prop);
Own here means return the property descriptor of prop property only if that property belongs
to the object obj and not on its prototype chain. If the property prop doesn’t exist on obj, it
returns undefined.
1. The value property of the property descriptor is the current value of the property
2. writable is whether the user can assign a new value to the property
3. enumerable is whether this property will show up in enumerations like for in loop or for
loop or Object.keys etc.
4. The configurable property tells whether the user has permission to change property
descriptors such as to change the value of writable and enumerable settings.
When you define a new property on an object using Object.defineProperty and pass an
empty {} descriptor, the default descriptor looks like below.
{
value: undefined,
writable: false,
enumerable: false,
configurable: false
}
Homework:
You can create or update multiple properties at once using Object.defineProperties which
takes two arguments. First argument is target object on which properties have to be
added/modified and second argument is object with key as property name and value as its
property descriptor. This function returns the target object.
let myObj = {
propOne: 10,
propTwo: 20,
};
//console.log(myObj);
myObj.propOne = 30;
//console.log(myObj);
//modify writable
Object.defineProperty(myObj, "propOne", { writable: false });
myObj.propOne = 50;
//console.log(myObj);
descriptor = Object.getOwnPropertyDescriptor(myObj, "propOne");
//console.log(descriptor);
//modify enumerable
//console.log(Object.entries(myObj));
//console.log(Object.keys(myObj)); //[ 'propOne', 'propTwo' ]
Object.defineProperty(myObj, "propOne", { enumerable: false });
//console.log(Object.keys(myObj)); //[ 'propTwo' ]
//console.log(myObj.propOne);
/**
* let obj = Object.create(prototype, {property: descriptor, ...})
*/
/*
let obj = {};
console.log(obj.__proto__ === Object.prototype);*/
let obj1 = { a: 1, b: 2 };
console.log(obj1);
console.log(obj1.__proto__.__proto__)
Multilevel Inheritance:
Multi-level inheritance can be defined as an inheritance in which a child class inherits the
properties from another child class, which inherited from the parent class and so on.
The multi-level inheritance has multiple base classes.
Class A
|
Class B
|
Class C
class Animal {
eat() {
console.log("eating");
}
}
class Lion extends Animal {
roar() {
console.log("roaring");
}
}
class BabyLion extends Lion {
weep() {
console.log("weeping");
}
}
let obj = new BabyLion();
obj.eat();
obj.roar();
obj.weep();
DOM:
The DOM stands for Document Object Model. It can simply be understood as a tree of
nodes created by the browser. Each of these nodes has its own properties and methods
which can be manipulated using JavaScript. The ability to manipulate the DOM is one of the
most unique and useful abilities of JavaScript.
How to Select Elements in the DOM?
In order to be able to manipulate an element in the DOM, you have to select that particular
element. There are 4 major ways of selecting elements:
1. getElementById(): The most common way to access an HTML element is to use the id of
the element. The id is case-sensitive. For example, the 'master' and 'Master' are totally
different ids. Once you have selected an element, you can add styles to the element,
manipulate its attributes, and traverse to parent and child elements.
3. getElementsByTagName(): This method accepts a tag name and returns all the elements
of the specified tag name in the order in which they appear in the document.
<script>
let btn = document.getElementsByTagName("button");
btn[0].addEventListener("click", function master() {
let masterElements = document.getElementsByTagName("p");
let masterEle2 = masterElements[2].innerHTML = "I need a Job";
console.log(masterEle2);
});
</script>
4. .querySelector() (CSS selector): This returns the first value that matches the selector it’s
given. This method can accept all CSS style selectors, allowing it to select by tag, class, or
ID.This method takes one argument, which is a CSS selector, and returns the first element
that matches the selector.
Everything in an HTML document is a node. Also the texts inside HTML elements are text
nodes. With the HTML DOM, you can navigate the node tree and access nodes in the tree
using node relationships (parent, child(ren), sibling(s) etc). New nodes can be created, and
all nodes can be modified or deleted.
1. Every node has exactly one parent, except the top node (which has no parent).
2. A node can have more than one child.
3. Siblings are nodes with the same parent.
How to get the parent element, siblings of an element, and children of an element using the
following node properties to achieve these things:
1. parentNode
2. childrenNodes
3. firstElementChild
4. lastElementChild
5. nextElementSibling
6. previousElementSibling
<div id="parent">
<div id="firstchild">I am the first child</div>
<p id="secondchild">I am the second child</p>
<h1>I am alive</h1>
<h2>Hello World</h2>
<p>I am the last child</p>
</div>
<script>
let lastElementChild =
document.getElementById("parent").lastElementChild;
console.log(lastElementChild);//<p>I am the last child</p>
19 Dec 2022
Lecture - 5
DOM:
<div id="parent">
<div id="firstchild">I am the first child</div>
<div id="secondchild">I am the second child</div>
<h1>I am alive</h1>
<h1>Hello World</h1>
<p>I am the last child</p>
</div>
<script>
let createEle = document.createElement("div");
createEle.innerHTML = "I am a frontend developer";
let parent = document.getElementById("parent");
parent.appendChild(createEle);
console.log(parent);
</script>
<div id="parent">
<div id="firstchild">I am the first child</div>
<div id="secondchild">I am the second child</div>
<h1>I am alive</h1>
<h1>Hello World</h1>
<p>I am the last child</p>
</div>
<script>
let createEle = document.createElement("div");
createEle.innerHTML = "I am a frontend developer";
let parent = document.getElementById("parent");
let secondchild = document.getElementById("secondchild");
parent.insertBefore(createEle, secondchild);
console.log(parent);
</script>
<script>
let createEle = document.createElement("h1");
createEle.innerHTML = "I am a frontend developer";
let parent = document.getElementById("parent");
let headers = document.getElementsByTagName("h1");
parent.replaceChild(createEle, headers[0]);
console.log(parent);
</script>
<div id="parent">
<div id="firstchild">I am the first child</div>
<div id="secondchild">I am the second child</div>
<h1>I am alive</h1>
<h1>Hello World</h1>
<p>I am the last child</p>
</div>
<script>
let parent = document.getElementById("parent");
let secondchild = document.getElementById("secondchild");
parent.removeChild(secondchild);
console.log(parent);
</script>
<script>
let buttonEle = document.getElementById("master");
buttonEle.addEventListener("click", addFunction);
function addFunction() {
buttonEle.classList.add("button");
console.log(buttonEle.classList);
}
</script>
<script>
let buttonEle = document.getElementById("master");
buttonEle.addEventListener("click", addFunction);
function addFunction() {
buttonEle.classList.remove("button");
console.log(buttonEle.classList);
}
</script>
<script>
let buttonEle = document.getElementById("master");
buttonEle.addEventListener("click", addFunction);
function addFunction() {
buttonEle.classList.toggle("button");
console.log(buttonEle.classList);
}
</script>
Event Handling:
Event handling:
HTML events are "things" that happen to HTML elements like the click of a button, input in a
text area, and so on. When an event occurs like the ones above, you can write JavaScript
code which we call an event handler that will be executed. These event handlers are
JavaScript functions. So when an event occurs on an element, the handler function is
executed.
Event listeners: Important in manipulating the DOM. To add an event listener to an element
or any DOM object, we need a method which is addEventListener(). This method is
preferred to the old one where we include the event to be handled in the html markup.
With this the JavaScript is separated from the html markup which makes it cleaner and
more readable.
Callback Function:
Note: The callback function is helpful when you have to wait for a result that takes time.
For example, the data coming from a server because it takes time for data to arrive.
function callMe() {
console.log("I am a callback function");
}
print("Swati", callMe);
function greet() {
console.log("Hello World");
}
function sayName(name) {
console.log("Hello" + " " + name);
}
20 Dec 2022
Lecture - 6
function sayName(name) {
console.log("Hello" + " " + name);
}
Event Bubbling:
When an event happens on an element, it first runs the handlers on it, then on its
parent, then all the way up on other ancestors.
The concept of event bubbling is used where the event handlers are invoked
when one element is nested on to the other element and are part of the same
event. We can understand event bubbling as a sequence of calling the event
handlers when one element is nested in another element, and both the
elements have registered listeners for the same event. So beginning from the
deepest element to its parents covering all its ancestors on the way to top from
bottom, calling is performed.
<div id="p2">
<div id="p1">
<button id="c1">I am a child button</button>
</div>
</div>
<script>
let grandParent = document.querySelector("#p2");
grandParent.addEventListener("click", function() {
console.log("Grand Parent is invoked");
});
let parent = document.querySelector("#p1");
parent.addEventListener("click", function() {
console.log("Parent is invoked");
});
let child = document.querySelector("#c1");
child.addEventListener("click", function() {
console.log("Child is invoked");
});
</script>
If one element in hierarchy does not have the specified event handler.
<div id="p2">
<div id="p1">
<button id="c1">I am a child button</button>
</div>
</div>
<script>
let grandParent = document.querySelector("#p2");
grandParent.addEventListener("click", function() {
console.log("Grand Parent is invoked");
});
let child = document.querySelector("#c1");
child.addEventListener("click", function() {
console.log("Child is invoked");
});
</script>
Stopping Bubbling:
Beginning from the target and moving towards the top is the bubbling i.e. starting
from the child to its parent, it moves straight upwards. But a handler can also
take the decision to stop the bubbling when the event has been processed
completely. In JavaScript, we use the event.stopPropagation () method.
<div id="p2">
<div id="p1">
<button id="c1" onclick="event.stopPropagation()">I am a child
button</button>
</div>
</div>
<script>
let grandParent = document.querySelector("#p2");
grandParent.addEventListener("click", function() {
console.log("Grand Parent is invoked");
});
let parent = document.querySelector("#p1");
parent.addEventListener("click", function() {
console.log("Parent is invoked");
});
let child = document.querySelector("#c1");
child.addEventListener("click", function() {
console.log("Child is invoked");
});
</script>
<div id="p2">
<div id="p1" onclick="event.stopPropagation()">
<button id="c1">I am a child button</button>
</div>
</div>
<script>
let grandParent = document.querySelector("#p2");
grandParent.addEventListener("click", function() {
console.log("Grand Parent is invoked");
});
let parent = document.querySelector("#p1");
parent.addEventListener("click", function() {
console.log("Parent is invoked");
});
let child = document.querySelector("#c1");
child.addEventListener("click", function() {
console.log("Child is invoked");
});
</script>
In order to stop the bubbling and also prevent the handlers from running on the
current element, we can use the event.stopImmediatePropagation () method. It is
another method that stops the bubbling and execution of all the other handlers. It
means if an element has more than one event handler on a single event, all the
event handlers bubbling will get stopped using this
event.stopImmediatePropagation () method.
<div id="p2">
<div id="p1">
<button id="c1" onclick="event.stopImmediatePropagation()">I am a
child button</button>
</div>
</div>
<script>
let grandParent = document.querySelector("#p2");
grandParent.addEventListener("click", function() {
console.log("Grand Parent is invoked");
});
let parent = document.querySelector("#p1");
parent.addEventListener("click", function() {
console.log("Parent is invoked");
});
let child = document.querySelector("#c1");
child.addEventListener("click", function() {
console.log("Child is invoked");
});
</script>
<div id="p2">
<div id="p1" onclick="event.stopImmediatePropagation()">
<button id="c1">I am a child button</button>
</div>
</div>
<script>
let grandParent = document.querySelector("#p2");
grandParent.addEventListener("click", function() {
console.log("Grand Parent is invoked");
});
let parent = document.querySelector("#p1");
parent.addEventListener("click", function() {
console.log("Parent is invoked");
});
let child = document.querySelector("#c1");
child.addEventListener("click", function() {
console.log("Child is invoked");
});
</script>
Event Capturing:
Netscape Browser was the first to introduce the concept of Event Capturing.
Event Capturing is opposite to event bubbling, where in event capturing, an event
moves from the outermost element to the target. Otherwise, in case of event
bubbling, the event movement begins from the target to the outermost element in
the file. Event Capturing is performed before event bubbling but capturing is used
very rarely because event bubbling is sufficient to handle the event flow.
<div id="p2">
<div id="p1">
<button id="c1">I am a child button</button>
</div>
</div>
<script>
let grandParent = document.querySelector("#p2");
grandParent.addEventListener("click", function() {
console.log("Grand Parent is invoked");
}, true);
let parent = document.querySelector("#p1");
parent.addEventListener("click", function() {
console.log("Parent is invoked");
}, true);
let child = document.querySelector("#c1");
child.addEventListener("click", function() {
console.log("Child is invoked");
}, true);
</script>
<div id="p2">
<div id="p1">
<button id="c1">I am a child button</button>
</div>
</div>
<script>
let grandParent = document.querySelector("#p2");
grandParent.addEventListener("click", function() {
console.log("Grand Parent is invoked");
}, true);
let parent = document.querySelector("#p1");
parent.addEventListener("click", function() {
console.log("Parent is invoked");
});
let child = document.querySelector("#c1");
child.addEventListener("click", function() {
console.log("Child is invoked");
}, true);
</script>
Shopping Cart Exercise:
<!--https://docs.google.com/document/d/
155aZjLMAtB04PNCMg1kAc19ovw6HfVqvBxLriO_66K4/edit-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Shoping cart</title>
<style>
div{
margin-bottom: 10px;
}
table{
border-collapse: collapse;
text-align: center;
margin: 30px auto;
}
th, td{
border: 1px solid black;
padding: 10px;
}
th{
min-width: 150px;
}
td[data-ns-test="grandTotal"], #total{
font-weight: bolder;
}
#container{
margin: 50px auto;
text-align: center;
}
</style>
</head>
<body>
<div id="container">
<h2>Shopping cart</h2>
<div>
<label for="item-name-input"><i><b>Item Name:</b></i></label>
<input type="text" id="item-name-input" name="name">
</div>
<div>
<label for="item-price-input "><i><b>Item
Price:</b></i></label>
<input type="number" id="item-price-input" name="price">
</div>
<div>
<button id="btn">Add</button>
</div>
<table id="table">
<thead>
<tr>
<th data-ns-test="item-name"><i><b>Item
Name</b></i></th>
<th data-ns-test="item-price"><i><b>Item
Price</b></i></th>
</tr>
</thead>
<tbody>
<tr>
<td data-ns-test="grandTotal">grandTotal</td>
<td id="total">0</td>
</tr>
</tbody>
</table>
</div>
<script>
let row = 1;
let button = document.getElementById("btn");
button.addEventListener("click", Add);
button.addEventListener("click", EmptyField);
function Add(){
let name = document.getElementById("item-name-input").value;
let price = document.getElementById("item-price-input").value;
price = Number(price);
let grandTotal = document.getElementById("total");
let total = grandTotal.innerText;
total = Number(total);
if(!name || !price){
alert("Enter all required fields.");
return;
}
let table = document.getElementById("table");
let newRow = table.insertRow(row++);
let nameCell = newRow.insertCell(0);
let priceCell = newRow.insertCell(1);
nameCell.innerHTML = name;
priceCell.innerHTML = price;
grandTotal.innerHTML = total + price;
}
function EmptyField(){
document.getElementById("item-name-input").value = "";
document.getElementById("item-price-input").value = "";
}
</script>
</body>
</html>
21 Dec 2022
Lecture - 7
JavaScript ES6:
1) JavaScript let
JavaScript let is used to declare variables. Previously, variables were declared
using the var keyword.
The variables declared using let are block-scoped. This means they are only
accessible within a particular
block.
2) JavaScript const
The const statement is used to declare constants in JavaScript. Once declared,
you cannot change the
value of a const variable.
const value1 = 5;
let value2 = 7;
value2 = 10;
(Remove /* */ in pairs to test and use the same pattern for all commented
snippets)
/*
let name = 'Swati';
{
let name = 'Avni';
console.log(name);//Avni
}
console.log(name);//Swati
*/
/*
const name = 'Swati';
{
const name = 'Avni';
console.log(name);//Avni
}
console.log(name);//Swati
*/
/*
var name = 'Swati';
{
var name = 'Avni';
console.log(name);//Avni
}
console.log(name);//Avni
*/
/*
let value1 = 2;
value1 = 3;
console.log(value1);
const value2 = 2;
//value2 = 3;//error
console.log(value2);
*/
This function
// function expression
let x = function(x, y) {
return x * y;
}
can be written as
/*
let x = function(x, y){
return x + y;
}
console.log(x(1, 2));
*/
/*
let x = (x, y) => x + y;
console.log(x(1, 2));
*/
/*
let x = (x, y) => {
let res = x + y;
return res;
};
console.log(x(1, 2));
*/
/*
let greet = () => console.log('Hello world');
greet();
*/
/*
let greet = x => console.log(`Hello ${x}`);
greet('Swati');
*/
/*
let age = 5;
let welcome = age < 18 ? () => { console.log("UnderAge") } :
() => { console.log("Adult") };
welcome();
//(condition)?(if true):(if false)
*/
4) JavaScript Classes
JavaScript class is used to create an object. Class is similar to a constructor
function.
class Person {
constructor(name) {
this.name = name;
}
}
sum(5);
sum(5, 6);
/*
function sum(x, y = 10){
console.log(x + y);
}
sum(5);
sum(5, 6);
*/
/*
function sum(x = 1, y = x, z = x + y){
console.log(x + y + z);
}
sum();
*/
/*
function sum(x = y, y = 1){
console.log(x + y);
}
sum();//error
sum(5);
sum(0, 1);
*/
/*
const sum = () => 15;
const calculate = function (x, y = x * sum()) {
return x + y; //10 + 150
}
const result = calculate(10);
console.log(result); //160
*/
/*
function test(x = 1) {
console.log(x);
}
test(undefined);
*/
7) JavaScript Destructuring
The destructuring syntax makes it easier to assign values to a new variable.
Object Destructuring:
let person = {
name: 'Swati',
age: 29,
gender: 'female'
}
/*
let { gender, name, age } = person;
console.log(name);
console.log(age);
console.log(gender);
*/
/*
let { gender: gender1, name: name1, age: age1 } = person;
console.log(name1);
console.log(age1);
console.log(gender1);
*/
let { name, ...rest } = person;
console.log(name);
console.log(rest);
Array Destructuring:
/*
let arr = ['one', 'two', 'three'];
let [x, y, z] = arr;
console.log(x, y, z);
*/
/*
let arr = [10];
let [x = 5, y = 7] = arr;
console.log(x, y);
*/
/*
//Swap
let x = 10;
let y = 20;
[x, y] = [y, x];
console.log(x, y);
*/
/*
let arr = ['one', 'two', 'three'];
let [x, , z] = arr;
console.log(x, z);
*/
//spread
let arr = ['one', 'two', 'three'];
let [x, ...y] = arr;
//let [,...x] = arr;
console.log(x, y);
9) JavaScript Promises
Promises are used to handle asynchronous tasks.
You pass the remaining arguments using ... syntax. Hence, the name rest
parameter. You use the spread syntax ... to copy the items into a single array.
Both the rest parameter and the spread operator use the same syntax. However,
the spread operator is used with arrays (iterable values).
function sum(x, y, z) {
console.log(x+y+z);
}
let num1 = [1, 2, 3, 4];
sum(...num1);
1) Data properties
2) Accessor properties
Data Property:
const student = {
// data property
firstName: 'Monica';
};
Accessor Property:
In JavaScript, accessor properties are methods that get or set the value of an
object.
For that, we use these two keywords:
get - to define a getter method to get the property value
set - to define a setter method to set the property value
JavaScript Getter:
In JavaScript, getter methods are used to access the properties of an object.
Note: To create a getter method, the get keyword is used.
JavaScript Setter:
In JavaScript, setter methods are used to change the values of an object.
Note: To create a setter method, the set keyword is used.
Setter must have exactly one formal parameter.
let student = {
firstName: 'Swati',
get getName() {
return this.firstName;
},
set changeName(newName) {
this.firstName = newName;
}
};
console.log(student.firstName);//Swati
console.log(student.getName);//Swati
student.changeName = 'Roshni';
console.log(student.getName);//Roshni
JavaScript Object.defineProperty():
In JavaScript, you can also use the Object.defineProperty() method to add
getters and setters.
let student = {
firstName: 'Swati'
};
Object.defineProperty(student, "getName", {
get: function() {
return this.firstName;
},
});
Object.defineProperty(student, "changeName", {
set: function(newName) {
this.firstName = newName;
},
});
console.log(student.firstName);
console.log(student.getName);
student.changeName = 'Roshni';
console.log(student.getName);
JS Operators:
JavaScript Operators:
What is an Operator?
In JavaScript, an operator is a special symbol used to perform operations on
operands
(values and variables). For example,
2 + 3; // 5
Here + is an operator that performs addition, and 2 and 3 are operands.
Others:
JavaScript this:
let a = this;
console.log(a); // Window {}
this.name = 'Swati';
console.log(window.name); // Swati
function greet() {
// this inside function
// this refers to the global object
console.log(this);
}
greet(); // Window {}
function Person() {
this.name = "Swati";
console.log(this);
}
Note: When this is used with ES6 classes, it refers to the object inside which it is
used(similar to constructor functions).
const person = {
name: "Swati",
age: 25,
person.greet();
const person = {
name: "Swati",
age: 25,
// inner function
function innerFunc() {
// this refers to the global object
console.log(this); // Window { ... }
console.log(this.age); // undefined
}
innerFunc();
},
};
person.greet();
22 Dec 2022
Lecture - 8
Example 1:
const greet = () => {
console.log(this);
}
greet(); // Window {...}
Example 2:
let greet = {
name: "Swati",
sayHi() {
let hi = () => console.log(this.name);
hi();
},
};
greet.sayHi();
Example 3:
let person = {
name: 'Swati',
greet() {
console.log(this);
console.log(this.name);
"use strict";
this.name = "Swati";
function greet() {
// this refers to undefined
console.log(this);
}
greet(); // undefined
Note: When using this inside a function with strict mode, you can use JavaScript
Function call().
'use strict';
this.name = 'Swati';
function greet() {
console.log(this.name);
}
greet.call(this); // Swati
The call() method calls a function by passing this and specified values as
arguments.
Static Methods:
class User {
// constructor(name1){
// this.name1 = name1;
// }
static getUser(x) {
return "Hello" + x;
}
}
//let object = new User("Swati");
//console.log(object.getUser());
console.log(User.getUser("Swati"));
Scope:
//global scope
let global = "Swati";
function func1() {
return global;
}
function func2() {
return func1();
}
console.log(func2());
//local scope
function func1() {
let a = 2;
let multiply = function() {
console.log(a*5);
}
multiply();
}
func1();
//Block scope
{
let a = 5;
}
//console.log(a);
Scope Chain:
1) JavaScript engine uses scopes to find out the exact location or accessibility of
variables and that particular process is known as Scope Chain.
2) Scope Chain means that one variable has a scope (it may be global or
local/function or block scope) is used by another variable or function having
another scope (may be global or local/function or block scope).
3) This complete chain formation goes on and stops when the user wishes to
stop it according to the requirement.
function func() {
global_var = 11;
let local_var = 3;
let nested_func1 = function() {
console.log(local_var);
}
let nested_func2 = function() {
console.log(global_var);
}
nested_func1();
nested_func2();
}
function func1() {
console.log(global_var);
}
func1();
func();
Closures:
pre-requisites:
function func() {
let local_var = 3;
function nested_func() {
console.log(local_var);
}
return nested_func;
}
let funcCall = func();
console.log(funcCall);
funcCall();
function greet(){
let name = 'Swati';
function displayName() {
return 'Hi' + ' ' + name;
}
return displayName;
}
let g1 = greet();
console.log(g1);
console.log(g1());
function calculate(x) {
function multiply(y) {
return x*y;
}
return multiply;
}
let multiply1 = calculate(3);
let multiply2 = calculate(4);
console.log(multiply1);
console.log(multiply1());//Nan
console.log(multiply1(6));//18
console.log(multiply2(2));//8
let a = 0;
function sum() {
function incSum() {
return a = a + 1;
}
return incSum;
}
let x = sum();
console.log(x());//1
console.log(x());//2
console.log(x());//3
a = a + 1;
console.log(a);//4
Value of “a” is increasing outside the function also with a = a + 1 in the second
last statement.
If you want to increase the value of “a” only inside the function, you can use a
closure like below:
//let a = 0;
function sum() {
let a = 0;
function incSum() {
return a = a + 1;
}
return incSum;
}
let x = sum();
let a = 5;
console.log(x()); //1
console.log(x()); //2
console.log(x()); //3
console.log(a);//5
23 Dec 2022
Lecture - 9
function Person() {
this.name1 = 'Swati'
}
let person1 = new Person();
Person.prototype.name1 = 'Roshni';
Person.prototype.age = 20;
/*
console.log(Function.__proto__ === Function.prototype);
console.log(person1.__proto__.__proto__.__proto__);
console.log(Person.__proto__.__proto__.__proto__);
*/
console.log(person1.name1);
console.log(person1.age);
console.log(Array.__proto__.__proto__.__proto__);
let arr = [];
console.log(arr.__proto__.__proto__.__proto__)
Callback Hell:
The phenomenon which happens when we nest multiple callbacks within a function is
called a callback hell. The shape of the resulting code structure resembles a pyramid
and hence callback hell is also called the “pyramid of the doom”.
TaskA(TaskB)
{
//TaskA work
TaskB()
}
24 Dec 2022
Lectures - 10 & 11
function apiCall() {
setTimeout(() => {
console.log("Data from API 1");
setTimeout(() => {
console.log("Data from API 2");
setTimeout(() => {
console.log("Data from API 3");
setTimeout(() => {
console.log("Data from API 4");
}, 5000);
}, 4000);
}, 3000);
}, 2000);
}
apiCall();
apiCall();
Promises:
We have ways to handle the same. Promises in JavaScript are one of them.
Pending
Fulfilled
Rejected
A promise starts in a pending state. That means the process is not complete. If
the operation is successful, the process ends in a fulfilled state. And, if an error
occurs, the process ends in a rejected state.
For example, when you request data from the server by using a promise, it will
be in a pending state. When the data arrives successfully, it will be in a fulfilled
state. If an error occurs, then it will be in a rejected state.
.then() is used to extract out the value of the fulfilled promise and .catch() is
used to extract out the reason for rejection (in case it gets rejected)
Promise Chain:
function asyncCallWithPromise1() {
let error = false;
return new Promise((resolve, reject) => {
setTimeout(() => {
if (!error) resolve("Data from API 1");
else reject("Error from API 1");
}, 3000);
});
}
function asyncCallWithPromise2() {
let error = false;
return new Promise((resolve, reject) => {
setTimeout(() => {
if (!error) resolve("Data from API 2");
else reject("Error from API 2");
}, 2000);
});
}
/*
Promise.all([asyncCallWithPromise1(), asyncCallWithPromise2()])
.then((values) => console.log(values))
.catch((error) => console.log(error));
*/
Promise.any([asyncCallWithPromise1(), asyncCallWithPromise2()])
.then((values) => console.log(values))
.catch((error) => console.log(error));
Benefits of Promises:
So, you still need to use callbacks while working with promises, but differently.
DOM Revision:
<div id="parent">
<div id="firstchild"><italic>I am the first child</italic></div>
<div id="secondchild">I am the second child</div>
<h1>I am alive</h1>
<h1>Hello World</h1>
<p>I am the last child</p>
</div>
<script>
let firstchild = document.getElementById("firstchild");
console.log(firstchild.innerHTML);
console.log(firstchild.innerText);
console.log(firstchild.textContent);
firstchild.innerHTML = "I am the first child";
console.log(firstchild.innerHTML);
</script>
2 Jan 2022
Lecture - 12
function f1() {
console.log("f1");
}
function f2() {
console.log("f2");
}
function f3() {
console.log("f3");
}
function main() {
console.log("main"); //printed
main();//call stack
Async Syntax
The keyword async before a function makes the function return a promise.
Await Syntax
The await keyword can only be used inside an async function.
The await keyword makes the function pause the execution and wait for a
resolved promise before it continues.
//console.log(getData());
3 Jan 2022
Lecture - 13
API Call:
JavaScript provides a few built-in methods and external open source libraries to
create and
interact with the API. A few possible methods to make an API call in JavaScript
are:
1. XMLHttpRequest
2. Fetch
3. Using Axios library
Fetch
XMLHttpRequest
Before JSON took over the world, the primary format of data exchange was XML.
XMLHttpRequest() is a JavaScript function that made it possible to fetch data
from APIs that returned XML data. XMLHttpRequest gave us the option to fetch
XML data from the backend without reloading the entire page. This function has
grown from its initial days of being XML only. Now it supports other data formats
like JSON and plaintext.
XMLRequest.send();
XMLRequest.onload = () => {
if (XMLRequest.status === 200) {
console.log("Request successful");
} else {
console.log("Error occurred");
}
console.log(JSON.parse(XMLRequest.response));
};
Postman: https://www.javatpoint.com/postman
4 Jan 2022
Lecture - 14
Axios
Axios is a promise-based HTTP client designed for Node.js and browser. With
Axios, we can easily send asynchronous HTTP requests to REST APIs and
perform create, read, update and delete operations. It is an open-source
collaboration project hosted on Github. It can be imported in plain Javascript or
with any library accordingly.
When we send a request to the API using axios, it returns a response. The
response object consists of:
Installation:
If you are using package manager like npm or yarn, then we can install Axios as
shown below.
npm install axios
// or
yarn add axios
2. Using CDN
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Now that we have successfully included Axios in our HTML file. Let's start
creating HTTP requests with it.
<script>
axios.get("https://reqres.in/api/users/2")
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
})
</script>
GET call
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
axios
.get("https://jsonplaceholder.typicode.com/posts")
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.log(error);
});
</script>
POST Call:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
axios("https://reqres.in/api/users", {
method: "POST", // or "PUT" with the url changed to, e.g
"https://reqres.in/api/users/2"
headers: {
"Content-type": "application/json",
},
data: { name: "Captain Anonymous" },
});
</script>
AJAX
What is AJAX?
AJAX stands for Asynchronous JavaScript And XML. It is not a programming
language. It is a technology
for developing better, faster and interactive Web Applications using HTML, CSS,
JavaScript and XML.
HTML : Hypertext Markup Language (HTML) is used for defining the structure of
a Web Application.
CSS : Cascading Style Sheet (CSS) is used to provide look and style to a Web
Application.
JavaScript : JavaScript is used for making a Web Application interactive,
interesting and user friendly.
XML : Extensible Markup Language (XML) is a format to store and transport data
from the Web Server.
HTML DOM : When a web page is loaded, the browser creates a Document
Object Model of the page.
XMLHttpRequest:
Before JSON took over the world, the primary format of data exchange was XML.
XMLHttpRequest() is a JavaScript function that made it possible to fetch data
from APIs that returned XML data. XMLHttpRequest gave us the option to fetch
XML data from the backend without reloading the entire page. This function has
grown from its initial days of being XML only. Now it supports other data formats
like JSON and plaintext.
JSON stands for Javascript Object Notation. JSON is a text-based data format
that is used to store and transfer data.
JSON Data
JSON data consists of key/value pairs similar to JavaScript object properties.
The key and values are written in double quotes
separated by a colon :. For example,
// JSON data
"name": "Swati"
JSON data requires double quotes for the key.
JSON Object
The JSON object is written inside curly braces { }. JSON objects can contain
multiple key/value pairs. For example,
// JSON object
{ "name": "John", "age": 22 }
JSON Array
JSON array is written inside square brackets [ ]. For example,
// JSON array
[ "apple", "mango", "banana"]
// JSON array containing objects
[
{ "name": "John", "age": 22 },
{ "name": "Peter", "age": 20 }.
{ "name": "Mark", "age": 23 }
]
JSON data can contain objects and arrays. However, unlike JavaScript objects,
JSON data cannot contain functions as values.
You can also use square bracket syntax [] to access JSON data. For example,
// JSON object
const data = {
"name": "Swati",
"age": 22
}
// accessing JSON object
console.log(data["name"]); // Swati
Though the syntax of JSON is similar to the JavaScript object, JSON is different
from JavaScript objects.
Use of JSON:
JSON is the most commonly used format for transmitting data (data interchange)
from a server to a client and vice-versa. JSON data are very easy to parse and
use. It is fast to access and manipulate JSON data as they only contain texts.
JSON is language independent. You can create and use JSON in other
programming languages too.
class CarModule {
#speed = 0;
#milesDriven = 0;
#accelerate1(amount) {
this.#speed += amount;
this.#milesDriven += this.#speed;
}
accelerate(amount) {
this.#accelerate1(amount);
}
getMilesDriven(){
return this.#milesDriven;
}
}
let testCarModule = new CarModule();
testCarModule.accelerate(5);//speed = 5 milesDriven = 5
testCarModule.accelerate(4);//speed = 9 milesDriven = 14
console.log(testCarModule.getMilesDriven());//14
console.log(testCarModule.speed);//undefined
Javascript setTimeout()
The setTimeout() method executes a block of code after the specified time. The
method executes the code only once.
Javascript setInterval()
The setInterval() method repeats a block of code at every given timing event.
setInterval(function, milliseconds);
Its parameters are:
5 Jan 2022
Lecture - 15
Type Coercion
Type coercion is the automatic or implicit conversion of values from one data
type to another
(such as strings to numbers). Type conversion is similar to type coercion
because they both convert
values from one data type to another with one key difference — type coercion is
implicit whereas type
conversion can be either implicit or explicit.
example:
console.log(sum); //59
JavaScript has coerced the 9 from a number into a string and then concatenated
the two values together, resulting in a string of 59. JavaScript had a choice
between a string or a number and decided to use a string.
//implicit
let value1 = "5";
let value2 = 9;
let sum = value1 + value2;
console.log(sum);
sum = value2 + value1;
console.log(sum);
sum = value1 - value2;
console.log(sum);
sum = 1 - "a";
console.log(sum);
//explicit
sum = Number(value1) + value2;
console.log(sum);
Switch
/**
* switch(expr){
* case 1:
* //code block
* break;
* case 2:
* //code block
* break;
* default:
* //code block
* }
*/
let day;
console.log(new Date().getDay());
switch (new Date().getDay()){
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 4:
day = "Thursday";
//break;
default:
day = "Wednesday";
}
console.log(day);