0% found this document useful (0 votes)
35 views55 pages

Advanced Js

some conecept of Javascript

Uploaded by

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

Advanced Js

some conecept of Javascript

Uploaded by

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

<!........................Introduction.............................!

>
JavaScript invented by Netscape company in 1996 and submit whole code to the ECMA
company.
First version: ECMAScript 1 comes in 1997 stand for European computer manufacutre
Association
ECMAScript 2 in 1998
ECMAScript 3 in 1999
ECMAScript 5 in 2009
ECMAScript 5.1 in 2011
ECMAScript 2015 in 2015(ES6)
ECMAScript 2016 in 2016(ES7)
ECMAScript 2017 in 2017(ES8)
ECMAScript 2018 in 2018(ES9)

In this course we will learn these topics;


Javascript ES6 and later version
Regular Expression
new Advanced Events and Web APIs.
DOM's new Methods and properties.

Must learn advanced javascript for better learning of React.js or next.js;

<!........................Advance Js - Let & Const


Variable.............................!>
Block means: if variable is declared in any block, then we cannot used this
variable outside the block. we can also use in inner block.

VAR:
var x="Hello";
re-declare: var x="WOrld";
re-assigned: x="Wow";
Scope of var is global. Global means we display the output in whole program or out
of body(globally).

if(condition){
var x="Hello";
}
document.write(x);

LET:
let x="Hello";
not re-declare: let x="WOrld"; (not)
re-assigned: x="Wow";

Scope of let is Block.Block means we display output in the if body or in the


structructure where var comes.

if(condition){
var x="Hello";
document.write(x);
}

CONST:
const x="Hello";
not re-declare: const x="WOrld"; (not)
not re-assigned: x="Wow"; (not)

Scope of const is Block.Block means we display output in the if body.

if(condition){
const x="Hello";
document.write(x);
}

Advanced Examples:
var:
Example 1:
function fun(love){

if(love){
var name = "Abdul";
var sname = "Manan";
}
document.write("My Name is=" + name + " " + sname);
}
fun(true);

Output:My Name is= Abdul Manan

Example 2:

var whowillwin = "india";


if(true){
var whowillwin = "Pakistan";
console.log(var whowillwin);
}
console.log(whowillwin);
output:
Pakistan
Pakistan

let:

Example 1:
function fun(love){

if(love){
let name = "Abdul";
const sname = "Manan";
}
document.write("My Name is=" + name + " " + sname);
}
fun(true);

Output:Reference Error.

Example 2:
var whowillwin = "india";
if(true){
var whowillwin = "Pakistan";
console.log(var whowillwin);
}
console.log(whowillwin);
output:
Pakistan
india

const:

Example 2:
var whowillwin = "india";
if(true){
var whowillwin = "Pakistan";
console.log(var whowillwin);
}
console.log(whowillwin);
output:
Pakistan
india

<!........................Advance Js - This Keyword.............................!>


const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};

What is this?
In JavaScript, the this keyword refers to an object.

The this keyword refers to different objects depending on how it is used:

In an object method, this refers to the object.


Alone, this refers to the global object.
In a function, this refers to the global object.
In a function, in strict mode, this is undefined.
In an event, this refers to the element that received the event.
Methods like call(), apply(), and bind() can refer this to any object

<!........................Advance Js - Template
Strings.............................!>

Template string or Template Literals:


var user = "Yahoo Baba";
var greet = "Hello" +user;

Template string:
var user="Yahoo Baba";
var greet=`Hello ${user}`; //Back tick below Esc key

Example
Without Template String
let user = "Yahoo Baba";
let marks = 350;
document.write("Hello " + user + " your marks is" +marks);
output: Hello Yahoo Baba your marks is 350.

With Template String

let user = "Yahoo Baba";


let marks = 350;
document.write(`Hello ${user} your marks is ${marks}`);
output same but method is different.

let user = "Yahoo Baba";


let marks = 350;
let hello=`Hello "${user}" your marks is ${marks}`;
document.write(hello);
console.log(hello);

Template String with Function

let firstName = "Yahoo";


let lastName = "Baba";

function fullname(firstName, lastName){


return `${firstName} ${lastName}`;
}

let hello = `Hello ${fullname(firstName, lastName)} Welcome to 2021.`;

document.write(hello);

<!........................Advance Js - Arrow
Functions.............................!>

Arrow Functions:
1st syntax:
function hello(){
console.log("Hello");
}
hello();

2nd syntax:
let hello=function(){
console.log("Hello");
}
hello();

Arrow function syntax:


let hello= () =>console.log("Hello");
hello();

Before
let welcome = function(name){
return `Welcome ${name}`;
}

console.log(welcome("Yahoo Baba"));

After

With Arrow Function

let welcome = (name) => {


return `Welcome ${name}`;
}

console.log(welcome("Yahoo Baba"));

Arrow Function with Multiple Parameters

let welcome = (name,age) => {


return `Welcome ${name} - ${age}`;
}

console.log(welcome("Yahoo Baba", 30));

<!........................Advance Js - Rest Operator.............................!


It accept multiple values in function in single variable by using three dots.

Rest operatore based on function with Multiple Arguments/Parameters:


funtion sum(num1, num2){
console.log(num1 + num2);
}
sum(20,30);
sum(20,30,40);
sum(20,30,40,50);

// sum only two arguments if 3 or 4 arguments are come then an error occured.
Solution:
function sum(){
let sum=0;

argument is a function which convert multiple parameters in an object. Basically it


accepts multiple parameters from function call and process them in function.
To print objects, we can use fro in loop.

for (let i in arguments){


sum +=arguments[i];
}
console.log(sum);
}

// if we pass one string and one integer value then above function failed. so rest
operator is used for this problem

3 dots means rest operator.


//for one variable and arguments
function sum(name, ...args){
console.log(arguments);
document.write(`Hello ${name} <br>
Your Marks : `);

let sum = 0;
for(let i in args){
sum += args[i];
}

document.write(sum);
}

sum("Yahoo Baba",10,20,30,40,50);

//for two variable and arguments


function sum(name,course, ...args){
console.log(arguments);
document.write(`Hello ${name} - ${course} <br>
Your Marks : `);

let sum = 0;
for(let i in args){
sum += args[i];
}

document.write(sum);
}

sum("Yahoo Baba","CS", 10,20,30,40,50);

/////////simple example

function sum(num1 ,num2, ...argument){


let sum =0;
for(var i in argument){
sum=sum + argument[i];
}
document.write(`${num1} your course is= ${num2} and Your marks sum= $
{argument[i]}`);
// document.write(sum);
// document.write(num1);
}
sum("manan","CS", 10,20,11,234,30,90);

<!........................Advance Js - Spread
Operator.............................!>

Rest operator convert rest value into array form and take multiple arguments.
Spread operator convert array value into arguments.spread operator always use at
function call time with three dots.

Rest Operator Example:

function sum(name, ...argument){


}
sum("Abdul Manan",10,20,30,40);

Spread Operator Example:

function sum(name, ...argument){

}
var arr=[50,60,70];
sum("Abdul Manan",...arr);//spread operator
Output; Abdul Manan 180
sum("Abdul Manan",10,20,...arr,30);

if we pass only array without spread operator it accepts only two arguments.
like
sum("Abdul Manan",arr);

function sum(name,...args){
console.log(arguments);

document.write(`Hello ${name} : `);

let sum = 0;
for(let i in args){
sum += args[i];
}

document.write(sum);
}

var arr = [20,30,40];


spread operator represent 3 dots.
sum("Yahoo Baba",...arr);
JavaScript

spread operator without Functions:

var arr =[1,2,3,4];


console.log(arr);
output: [0]: 1,[1]: 2,[2]: 3,[3]: 4

console.log(...arr);
output: 1,2,3,4

Spread Operator with Objects

var obj1 = {
name : "Yahoo Baba",
course : "Btech"
}

var obj2 = {
age : 25
}

var obj3 = {...obj1, ...obj2};

console.log(obj3);

output:
name: "Yahoo Baba"
course: "Btech"
age: 25

<!........................Advance Js - Object
Literals.............................!>
let name = "Yahoo Baba",
Old Method:
let obj ={
name:name
};

New Method:
let obj ={
name
};

Before
let name = "Yahoo Baba",
course = "Btech";

var obj = {
name : name,
course : course
};

console.log(obj);
console.log(obj.name);
JavaScript

With Object Literals


let name = "Yahoo Baba",
course = "Btech";

var obj = {
name,
course
};

console.log(obj);
console.log(obj.name);
JavaScript

Variable as a property name


let n = "name";

var obj = {
[n] : "Yahoo Baba",
course : "Btech",
detail(){
return `${this.name} is student of ${this.course}`;
}
};
JavaScript

Computed property name


let name = 'student';

var obj = {
[name + "name"] : "Yahoo Baba",
course : "Btech",
detail(){
return `${this.studentname} is student of ${this.course}`;
}
};
JavaScript

Declare function in object before Object Literals


var obj = {
name,
course,
detail : function(){
return `${this.name} is student of ${this.course}`;
}
};

console.log(obj.detail());
JavaScript

Declare function in object with Object Literals


var obj = {
name,
course,
detail(){
return `${this.name} is student of ${this.course}`;
}
};

console.log(obj.detail());

// New Way to view object's property value


console.log(obj['name']);
console.log(obj['detail']());
JavaScript

Return Function value as a Object Literal


function student(fname, lname, course){
let fullname = fname + " " + lname;

return {fullname, course};


}

console.log(student(fname, lname, course));


JavaScript

Let take variable as Object


function student(fname, lname, course){
let fullname = fname + " " + lname;
return {fullname, course};
}

let s = student("Ram","Kumar", "Bcom");

console.log(s.fullname);
console.log(s.course);

<!........................Advance Js - Destructuring
Array.............................!>
let user = ["Yahoo Baba", 25, "Delhi"];

let name= user[0];


let age= user[1];

let[name,age] = user;

let user = ["Yahoo Baba", 25, "Delhi"];

let [name, age, city] = user;

console.log(name);
console.log(age);
console.log(city);

Using Default Value


let user = ["Yahoo Baba", 25, "Delhi"];

let [name, age = 20, city] = user;


JavaScript

With Nested Array


let user = ["Yahoo Baba", 25, "Delhi", ["Male", 25000]];
let [name, age = 20, city,[gender, salary]] = user;

console.log(gender);
console.log(salary);
JavaScript

Using Rest Operator


let user = ["Yahoo Baba", 25, "Delhi"];

let [name, ...args] = user;

console.log(name);
console.log(args);
JavaScript

Using with function


function user([name, age = 20, city]){
console.log(name);
console.log(age);
console.log(city);
}

user(["Yahoo Baba", 25, "Delhi"]);


JavaScript

Return an Array from Function


function user(){
return ["Yahoo Baba", 25, "Delhi"];
}

let [name, age = 20, city] = user();

console.log(city);

<!........................Advance Js - Destructuring
Object.............................!>
let user = {
name : "Yahoo Baba",
age : 25,
city : "Delhi"
}

let {name, age, city} = user;

console.log(city);
JavaScript

Using Alias Name


let user = {
name : "Yahoo Baba",
age : 25,
city : "Delhi"
}

let {name : n,age : a,city : c} = user;

console.log(n);

<!........................Advance Js - OOP
Introduction.............................!>
Object Oriented Programming is a coding methodology/style/pattern
code more Modular and Reusable
Well Organized Code
Easier to debug.
JS OOP is Best for medium to large website projects.
and used in most of the framework like ReactJs, NodeJs, vuejs, nextjs etc.

Class and Objects:


class is the combination of properrties and methods. properteis are data members
and methods
are member functions. Objects are combination of properties and methods.

Example of Properties:
var a,b,c;
let c,d,e;
const e,f;

Example of Methods:
sum(){
c=a+b;
return c;
}

class hello{

message(){
console.log("Hello Everyone");
}

}
// in the above example a class hello contains a functioned named message.one class
may be
of multiple functions.

let a = new hello();


a.message();
//here a is the object and hello is the new class.

console.log(typeof a);

a.message();
//here a is the object calling a function named as message.

3 Type of Methods in js oop:


1-Constructor : constructor function automatically calls when an object of that
class is created.

constructor(){
console.log("Constructor Function");
}

2-Prototype : defined by programmer. Like

message(){
console.log("Prototype Function")
}
3-Static funtion: defined with keyword static and function name. name defined by
programmer.
static method can be used without object.

static name(){
console.log("static Function");
}

Constructor function in class


class student{
constructor(){
console.log("Constructor Function")
}
}

let a = new student();

Initilize Property
class student{
constructor(){
let studentname;
}
}

let a = new student();

a.studentname = "Yahoo Baba";


JavaScript

Initialize Property with constructor


class student{
constructor(name){
console.log("Hello " + name);
}
}

let a = new student("Yahoo Baba");


JavaScript

Prototype method
class student{
constructor(name){
this.studentname = name;
}
hello(){
console.log("Hello " + this.studentname);// this keyword represent studentname
of
of current class.
}
}

let a = new student('Yahoo Baba');


a.hello();
Output: Hello Yahoo baba
Static Method
class student{
static staticMethod(){
console.log("Static Method");
}
}

student.staticMethod();

<!........................Advance Js - Class
Inheritance.............................!>
Inheritance: class A can be used properties and methods of another class.
Let's suppose class A will be used properties of class B and another class used
properties
of class A or B.Class A is called parent class,Base class,Super class and Class B
is called
derived class,Child class.
*if one class is used to inherit one another class then it is called single level
inheritance.
*if one class is used to inherit multiple classes then it is called multiple
inheritance.
*if one class is used properties of one class and inherited by another class then
it is
called multilevel inheritance.
*if class B is inherit properties of class A and class C inherit properties of
class B
then it is called hirerchical inheritance.extends keyword is used to inherit
classes.

Examples:
class fruits{
//properties and methods
}

class vegetables extends fruits{


//properties and methods
}

let f=new fruits(); //this object is used only fruit class methods and properties.
let v=new vegetables(); //this object is used both classes functionality. First
enter in
class vegetables and take reference and then enter in class fruits. First display
the class
fruit functionality and then display the result of class vegetables.

class employee{
constructor(){
console.log("constructor Function Employee");
}
}

class manager extends employee{

let a = new manager();


JavaScript

Use Consturctor of derived class


class employee{
constructor(){
console.log("constructor Function Employee");
}
}

class manager extends employee{


constructor(){
super();
console.log("constructor Function Manager");
}
}

let a = new manager();


JavaScript

Advance Example
class employee{
constructor(name, age, salary){
this.empname = name;
this.empage = age;
this.empsalary = salary;
//console.log("Constructor : Employee");
}

info(){
document.write(`<h3>Employee Class</h3>
Name : ${this.empname}
<br>
Age : : ${this.empage}
<br>
Salary : $
{this.empsalary} <br>`)
}
}

class manager extends employee{

info(){
let ta = 1000;
let pa = 300;
let totalsalary = this.empsalary + ta + pa;

document.write(`<h3>Manager Class</h3>
Name : ${this.empname}
<br>
Age : : ${this.empage}
<br>
Salary : ${totalsalary}
<br>`)
}
}

class test extends manager{

let a = new test("Yahoo Baba", 25, 20000);


//let b = new employee("Ram Kumar", 22, 12000);

a.info();
//b.info();

<!........................Advance Js -Exports and Imports


Modules.............................!>

what is modules?
suppose we have two javascript files File1.js and File2.js
File1.js contains variables,functions and classes and we want to used data of
File1.js
in File2.js. this method is called modules.
Advantages:
*Re-usability increase.(we used data of 1 file in others files many times).
*Decrease time of HTML file loading.

when we want to use data of one file into another file then we used two functions
import and export.

How to work with Modules?

1. File1.JS Data:used keyword export for reference


export describes that this variable, function or class we can use in another file.

let name ="Abdul Manan";


export let name ="Abdul Manan";

export function hello{


//body
}

export class user{


//body
}

2. File2.js Data: (used data of File1.js)


for using data from another file, use import keyword

import {var name,function name,class name} from './name of reference file';


like as....

import {name} from './File1.js';


import {hello} from './File1.js';
import {user} from './File1.js';
//we can used variables,function and classes in one line.like
import {name,hello,user} from './File1.js';
console.log(name);
hello();
let a=new user();

3. After this include File2.js in HTML File.


<script type="module" src="./File2.js"></script>
in the start of path, (./) represents this file is based on modules.
<script type="module" src="./js/File2.js"></script>

in javascript modules work with live server like xamp,wamp server


or install live server extension on Editor.

Practical Work:

Folder name:modules
file name:index.html, library.js like file1.js and main.js like file2.js

include main.js file in index.html file in head tag.


<script type="modules" src="./main.js"></script>

if we check console then we find Runtime{action : "tab_url_change",recongnizing :


false}

///////////////////////code in library.js file:

//variable
export let message= "ES6 modeuls";

//function
export function user(){
console.log("HEllo this is function");
}
//template string
export function user(name){
console.log(`Hello ${name}`);value received from where a function call.
}
like that: user("Abdul Manan");//in main.js file

//return value of template string


export function user(name){
return `Hello ${name}`;value received from where a function call.
}
like that: console.log(user("Abdul Manan"));//in main.js file

// classes
export class test{

constructor(){
console.log("construtor method");
}
}

Shortcut method of export(remove previous export) and add at the end of file:
export{message, user, test};

### Default method in library.js


export default function(){
console.log("Hello");
}

### Aggregate Modules in libraray file:


function:
function user(){
return `Hello`;
}

export { user };

create new file in folder modules name:bridge.js:


filename:bridge.js (work in between library.js and main.js file)

export {user} from "./library.js"; in bridge.js file

///////////////////////code in main.js file:

import {message,user,test} from './library.js';

console.log(message);//can be used in document like


document.body.innerHTML=message;
user();//function call and output:HEllo this is function
//template string
user("Abdul Manan");

//for class
let a=new test();

Shortcut method of import(use alias):


import {message,user as us,test} from './library.js';
us();
*if file is too large and we want to used all var,function and classes
in other file then used:
import * as manan from "./library.js";
console.log(manan.message);
console.log(manan.user("Abdul Manan"));
let a= new manan.test();

### Default function in main.js


import { default as yahoo } from "./library.js";
call default function with alias name:
yahoo();output:Hello

### Aggregate Modules in main file:


import {user} from "./bridge.js";
console.log(user());
output: Hello

use export keywork in the central file always like bridge.js is a mid file
between library.js and main.js

<!........................Advance Js - Generators.............................!>
<!........................Advance Js - Promises.............................!>

What is Promise?
suppose your friend call and want to meet with you.you says that we meet tomorrow.
you take a promise that we meet tomorrow together.

Promise Object Properties


A JavaScript Promise object can be:

Pending
Fulfilled
Rejected

promise is divided into three stages:


1.Pending: (jab tk kal ka din ni ata promise is in pending)
2.fulfilled: if you meet with friend toworrow then promise is fulfilled.(Resturant
or any other place)
3.Rejected: not meet with friend tomorrow because of any reason.(see you meet
another day)

in javascript promise method work same like above example:


In promise method a condition will come,
Promise(condition) n
### if condition is fullfilled then we say resolved() in Js.if fulfilled then we
call a function name .then() in javascript.
### if condition is not fulfilled or failed then we say reject(). if failed then we
call a funciton name .catch() in javascript.
## Both then() and catch() functions are callback functions.
## resolve() or reject() function defined by programmer to any name.
## if rosolve() is true then .then() function call automatically and if reject()
method is true then catch() call automatically.

#Syntax of Promise in JS:

let prom = new Promise();

//defined a function in promise method:


let prom = new Promise(function(){

});

// gives two parameters in promise method. if promise is fulfilled then call


resolve function and if
reject method true then call reject method.

let prom = new Promise(function(resolve, reject){


if(condition){
//if condition true
resolve();

}
else{
reject();
}
});

if(condition){
//if condition true
resolve("Here is success");

}
else{
reject("Here is failure");
}
});
// call when resolve() function is true.
let onfulfillment = (result)=>{
console.log(result);
}

// call when reject() function is true.


let onRejection = (error)=>{
console.log(error);
}

///call above two methods


prom.then(onfulfillment );
prom.catch(onRejection );

/////////////////////////////////////////////
resolve is for success case and reject is for error or failure.
if function is resolve then prom.then() function call
if function is reject then prom.catch() method call
here prom is variable name.

let prom= new Promise(function(resolve,reject){


if(condion){
resolve("Here is success");
//if condion is true then resolve function call onfulfillment function.
}else{
reject("Here is failure!");
//if condion is false then reject function call onRejection function.
}
});

prom.then(onfulfilment);
prom.catch(onRejection);
//onfulfilment
let onfulfilment=(result)=>{
console.log(result);
}
//onRejection
let onRejection=(error)=>{
console.log(error);
}

Use call back function .then and .catch method with onfulfilment and onRejection
like as
promo.then(onfulfilment);
promo.catch(onRejection);
////////////////////////////////////////////
##### Practical work

Example 1:
<script>
let complete=true; //check value of complete in promise true or false

let prom = new Promise(function(resolve,reject){


if(complete){
resolve("Function is successful");
}else{
reject("Function is failed");
}
});
console.log(prom); //here prom is object
output will be : Function is successful
and vice versa.
<script>

Example 2:

<script>
function prom(complete){

return new Promise(function(resolve,reject){


if(complete){
resolve("Function is successful");
}else{
reject("Function is failed");
}
});

}//prom function closed


console.log(prom(false));//false value will be passed to prom function
as a complete variable in this example.
output will be : Function is failed
</script>

Example 3: implementation of onfulfilment and onRejection


<script>
function prom(complete){

return new Promise(function(resolve,reject){


if(complete){
resolve("Function is successful");
}else{
reject("Function is failed");
}
});

}//prom function closed


console.log(prom(false));

Result of resolve method come in result variable.


Result of reject method come in error variable.
by using arrow function

let onfulfilment = (result) => {


console.log(result);
}
let onRejection = (error) => {
console.log(error);
}

prom is function name.use callback functions then and catch

prom(true).then(onfulfilment );//if resolve)()


prom(true).catch(onRejection );//if reject()
output will be: //Function is successful

shorthand: //prom(true).then(onfulfilment ).catch(onRejection );

</script>

Example 4: use of setTimeout function

<script>

function prom(complete){

return new Promise(function(resolve,reject){


console.log("pending stage"); //pending stage
OR console.log("fetching data, please wait");

//set if condition in timeout() function.


setTimeout(()=>{
if(complete){
resolve("I am successfell");
}else{
reject("I am failure");
}
}, 3000) //run this function after three seconds or 3000 milli seconds.
});
}

let onfulfilment = (result) => {


console.log(result);
}
let onRejection = (error) => {
console.log(error);
}

prom(true).then(onfulfilment );
prom(true).catch(onRejection );

output will be:


//fetching data, please wait
//fetching data, please wait //2 outputs: because we call prom function two
times.
for one time printing prom function, use catch and then
methods in combined.
like
this://prom(true).then(onfulfilment ).catch(onRejection );
prom(true).then(onfulfilment ).catch(onRejection );

// after 3 seconds setTimeout function run and print "i am successful "

</script>

Example 5: we can make onfulfilment and onRejection method in then and catch
method.

<script>

function prom(complete){

return new Promise(function(resolve,reject){


console.log("pending stage");

//set in timeout() function.


setTimeout(()=>{
if(complete){
resolve("I am successfell");
}else{
reject("I am failure");
}
}, 3000) //run this function after three seconds or 3000 milli seconds.
});
}

let onfulfilment = (result) => {


console.log(result);
}
let onRejection = (error) => {
console.log(error);
}

//prom(true).then(onfulfilment );
//prom(true).catch(onRejection );
prom(true).then(onfulfilment ).catch(onRejection );

output will be: pending stage run only one time now.
//fetching data, please wait
// after 3 seconds setTimeout function run and print "i am successful "

//another way
prom(true).then((result) => {
console.log(result);
});
prom(true).catch((error) => {
console.log(error);
});

// call the promise method


console.log(prom(true)); or
console.log(prom(false));

</script>

Example 6:

<script>

function prom(complete){

return new Promise(function(resolve,reject){


console.log("pending stage");

//set in timeout() function.


setTimeout(()=>{
if(complete){
resolve("I am successfell");
}else{
reject("I am failure");
}
}, 3000) //run this function after three seconds or 3000 milli seconds.
});
}

//another way
prom(true).then((result) => {
console.log(result);
});
prom(true).catch((error) => {
console.log(error);
});
OR
prom(true).then((result) => {
console.log(result);
}).catch((error) => {
console.log(error);
});

output will be:


//fetching data, please wait
// after 3 seconds setTimeout function run and print "i am successful "

</script>

Example 7:
passing two variable value and divide them.
<script>

function prom(a,b){

return new Promise(function(resolve,reject){


console.log("pending stage");
var c= a/b;

//set in timeout() function.


setTimeout(()=>{
if(a,b){
resolve(`Your answer is: ${c}`);//use back tick above Tab key
}else{
reject("I am failed to calculate");
}
}, 2000) //run this function after two seconds or 2000 milli seconds.
});
}

//another way
prom(true).then((result) => {
console.log(result);
});
prom(true).catch((error) => {
console.log(error);
});
OR
prom(5,2).then((result) => {
console.log(result);
}).catch((error) => {
console.log(error);
});

output will be:


//pending stage
// after 2 seconds setTimeout function run and print "Your answer is: 2.5 "

prom(5,0).then((result) => {
console.log(result);
}).catch((error) => {
console.log(error);
});
//error occured: Failed to calculate

</script>

you can implement ajax by using JQuery cdn link in promises.

<!........................Advance Js - Promise.All.............................!>
supoose we have multiple promises. To solve multiple promises we can use
Promise.all() function. These promises have resolve() or reject() . if all promises
resolve() successfully then we can run .then() function if anyone from is reject
then .catch() method is executed.

First Promise:
let p1=new Promise(function(resolve,reject){
console.log("First Promise");
resolve("First");
});

Second Promise:
let p2=new Promise(function(resolve,reject){
console.log("second Promise");
resolve("second");
});

Promise.all([p1,p2]);///we can take multiple promises in an array form.


use only one time .then() and .catch() method in promise.all();

Promise.all([p1,p2]).then().catch();

What is Promise.all()?
promise.all() function check all or multiple promises by variable name.
//Promise.all([p1,p2]);

promise all function combines all promises.


resolve or reject:
if all the promises are resolve then .then() function is called.
if any one of the promise method is failed from all promises then catch() method is
called.

Promise Syntax:

1st Promise:

let p1 = new Promise(function(resolve, reject){


console.log("First Promise");
resolve("First");
)};

let p2 = new Promise(function(resolve, reject){


console.log("Second Promise");
resolve("second");
)};
Array:

Promise.all([p1,p2]);

use then() and catch() method combined.


Promise.all([p1,p2]).then().catch();

use then() and catch() function one time.

<script>
### first promise

let p1=new Promise((resolve,reject) =>{


setTimeout(()=> {
console.log('The first promis has solved');
resolved(10);

},1*1000);

### Second Promise


let p2=new Promise((resolve,reject) =>{
setTimeout(()=> {
console.log('The second promis has resolved');
resolved(20);

},2*1000);

### Third Promise


let p3=new Promise((resolve,reject) =>{
setTimeout(()=> {
console.log('The third promis has resolved');
resolved(30);

},3*1000);
)};
check above three promises in one line.
you can use
Promise.all([p1,p2,p3]).then().catch(); like that

promise.all([p1,p2,p3]).then((result)=>{
console.log(`Results: ${results}`);
}).catch((error)=>{
console.log(`Error: ${error}`);
});
output will be:
The first promis has solved
The second promis has resolved
The third promis has resolved
Result: 10,20,30

</script>

Example 2: use of for in loop in promise.all()

### first promise


let p1=new Promise((resolve,reject) =>{
setTimeout(()=> {
console.log('The first promis has solved');
resolved(10);

},1*1000);

### Second Promise


let p2=new Promise((resolve,reject) =>{
setTimeout(()=> {
console.log('The second promis has resolved');
resolved(20);

},2*1000);

### Third Promise


let p3=new Promise((resolve,reject) =>{
setTimeout(()=> {
console.log('The third promis has resolved');
resolved(30);

},3*1000);
)};

var total = 0;
promise.all([p1,p2,p3]).then((result)=>{
for(var x in result){
total = total + result[x];
}console.log(`Results: ${results}`);
console.log(`Total: ${total}`);

}).catch((error)=>{
console.log(`Error: ${error}`);
});
output will be:
The first promis has solved
The second promis has resolved
The third promis has resolved
Result: 10,20,30
Total : 60

Example 3: if any one promise is reject. then catch() method run.

### first promise

let p1=new Promise((resolve,reject) =>{


setTimeout(()=> {
console.log('The first promis has solved');
resolved(10);

},1*1000);

### Second Promise


let p2=new Promise((resolve,reject) =>{
setTimeout(()=> {
console.log('The second promis has failed');
reject("OOPs Promise Failed!");

},2*1000);

### Third Promise


let p3=new Promise((resolve,reject) =>{
setTimeout(()=> {
console.log('The third promis has resolve');
resolved(30);

},3*1000);
)};

var total = 0;
promise.all([p1,p2,p3]).then((result)=>{
for(var x in result){
total = total + result[x];
}console.log(`Results: ${results}`);
console.log(`Total: ${total}`);

}).catch((error)=>{
console.log(`Error: ${error}`);
});
output will be:
The first promis has solved
The second promis has failed
Error: OOPs Promise Failed!
The third promis hase resolved

Example 4: short method to create promise

### first promise

let promiseCall= function (returnData,message) =>{


return function(resolve,reject){
setTimeout(()=> {
console.log(`The ${message} promis has resolved`);
resolved(returnData);

},returnData*1000);

}
};
let p1 = new Promise(promiseCall(10,"first"));
let p2 = new Promise(promiseCall(20,"second"));
let p3 = new Promise(promiseCall(30,"third"));

var total = 0;
promise.all([p1,p2,p3]).then((result)=>{
for(var x in result){
total = total + result[x];
}console.log(`Results: ${results}`);
console.log(`Total: ${total}`);

}).catch((error)=>{
console.log(`Error: ${error}`);
});
output will be:
The first promis has solved
The second promis has resolve
The third promis hase resolved
Result: 10,20,30
Total: 60

Example 5: Reject Method

### first promise

let promiseCall= function (returnData,message) =>{


return function(resolve,reject){
setTimeout(()=> {
console.log(`The ${message} promis has resolved`);
resolved(returnData);

},returnData*1000);

}
};
let p1 = new Promise(promiseCall(10,"first"));
let p2 = new Promise(promiseCall(20,"second"));
let p3 = new Promise(promiseCall(30,"third"));
let p4 = new Promise(function(resolve,reject){
reject("The 4th promise has rejected");
});

var total = 0;
promise.all([p1,p2,p3,p4]).then((result)=>{
for(var x in result){
total = total + result[x];
}console.log(`Results: ${results}`);
console.log(`Total: ${total}`);

}).catch((error)=>{
console.log(`Error: ${error}`);
});
output will be:
Error : The 4th promise has rejected
The first promis has solved
The second promis has resolve
The third promis hase resolved

<!........................Advance Js - Ajax.............................!>

AJAX Stands for Asynchronous JavaScript and XML.


AJAX is a technique for creating fast and dynamic web pages.

When we use AJAX?


when we want to load the spacific part of the web page. Then we use ajax and this
is
working fast.

How Ajax works?


XML HttpRequest:
Text File
XML Data
JSON Data

5 Steps:
readyState

readyState0
readyState1
readyState2
readyState3
readyState4
0:request not initialized
1:server connection established
2:request received
3:processing request
4:request finished and response is ready

if response give text then write responseText


if response give XML then write responseXML

http Status code: status has three mainly codes


200: "OK"
403: "Forbidden"
404: "Not Found"

Syntax of AJAX?

var xhttp = new XMLHttpRequest();

//check readystate working


xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status ==200){
document.getElementById("demo").innerHTML = this.responseText;
}

};

two methods:
xttp.open("method","file_name","async-mode");
xttp.open("GET","file-name.txt",true);
xhttp.send();

Practical Work:
file-name: ajax-text.html,readme.txt

readme.txt
Hello this is text file.

ajax-text.html

<body>
<p id="demo">Here we load Data.</p>
<button onclick = "loadData()">Click Me</button>
<scrip>
function loadData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
//console.log(this.responseText);
document.getElementById("demo").innerHTML = this.responseText;
}else if(this.readyState == 4 && this.status == 404){

document.getElementById("demo").innerHTML = "File not found";


}
};

xhttp.open('GET',"readme.txt",true)
xhttp.send();
}

</script>

</body>
// fake json data (search on google for fake data)

<!........................Advance Js - Fetch API.............................!>


//AJAX
JQuery:
$.ajax();
$.get();
$.post();

//JavaScript
XMLHttpRequest

What is Fetch() Method::??


we done every thing which make thorough Ajax.
WE make CRUD system with server by the help of fetch method.
insert,update,delete and read.

we can use Fetch() method where we use ajax.

Syntax of Fetch() method:


fetch();
fetch(file/URL); // return a promise

fetch(file/URL).then(); //return promise

//file me ham ko jo data mily ga wo hum function me send kary gy.

fetch(file/URL).then(function(response){ // response come from server


return response.data;
// if data is in text format then use text() method and if
data is in json format then use json() method
});
ye wala data jo hy wo dosry .then() function me jaye ga.see below

//promise success result


fetch(file/URL).then(function(response){
return response.data;
}).then(function(result){
console.log(result);
//final result, file jo bhi response return kry gi wo response funtion me or jo
response
function return kry ga wo wala result variable me aa jaye ga.
});
//promise success result

//promise fail result


//if an error occurred

fetch(file/URL).then(function(response){
return response.data;
}).then(function(result){
console.log(result);
}).catch(function(error){
console.log(error);
});
//if promise is success then response goes into in function result otherwise goes
in catch function and store in error variable.

fetch() method works on Live Server

Two files:
readme.txt
Hello this is text file
index.html
<script>

fetch("readme.txt") //file name


.then(function(response){
console.log(response.text());
return response.text();
})
.then(function(data){
console.log(data);
document.write(data);
return response.text();
})
.catch((error){
console.log("Can't fetch Data"));
});

//by using arrow function


readme.tx =Hello this is text file
fetch("readme.txt")
.then((response) => response.text( ))
.then((data) => document.write(data));

go to chorom and type


fake json data
now pic data from chorom in the response option
add link in fetch mehod and check in console and browser screen

//it will come in json format


fetch("https://jsonplaceholder.typicode.com/users")
.then((response) => response.json())
.then((data) => console.log(data))
//.then((data) => document.write(data))
.catch((error) => console.log(error));
</script>

<!........................Advance Js - Async & Await.............................!>


Normal Function:
function test(){
//code here
}
if we write async keyword before normal function it becomes async function.

Async Function:
async function return always promise. use keyword async befor function like
A promise is resolved() or reject()
async function test(){
//code here
}
////promise function has some complications. like each time we have call
resolve() and reject() methods. when we call resolve() and reject() then
our .then() and catch() method call.

////async function remove these complications. we just call directly .then()


and catch() method.

Example 1:
<script>
async function test(){
return "HELLO";
}
console.log(test());
output:HELLO

</script>

Example 2: USE OF ASYNC FUNCTION


<script>
async function test(){
return "HELLO";
}
console.log(test());
return a promise which is fulfilled.

</script>

Example 3: use of then and catch method


<script>
async function test(){
return "HELLO";
}

test().then(result() =>{
console.log(result);
});
output: HELLO
</script>

Example 4:another method to create function


<script>
let test = async function(){
return "HELLO";
}
test().then(result() =>{
console.log(result);
});

</script>

Example 5: by using arrow function


<script>
let test = async () => "HELLO"; //arrow function

test().then(result() =>{
console.log(result);
});
output: HELLO
</script>

Await Method:

await method work in async function.

async function test(){

console.log("A");
await console.log("B");
console.log("C");
}

test();
console.log("D");
console.log("E");
this means that First of all "A" will be printed and then cursor on await
function. it will stop processing in function and send to the outside the
function to print other statements. when outside statements print then
it will continue from where it will be skipped.
//////await ky baad ka code run nahi hota jab wo code apna kam complete nahi
kar leta.
//its main use is when we fetch data from server, when we use javascript
function fetch() method.
////fetch() will fetch data from server in the format of json or text.

Practicle:
Example 1:
<script>
async function test(){
console.log("Message 2");
console.log("Message 3");
console.log("Message 4");
}
console.log("Message 1");
test();
console.log("Message 5");
output: Message 1
Message 2
Message 3
Message 4
Message 5

</script>

Example 2: await method used


<script>
async function test(){
console.log("Message 2");
await console.log("Message 3");
console.log("Message 4");
}
console.log("Message 1");
test();
console.log("Message 5");
output: Message 1
Message 2
Message 3
Message 5
Message 4

</script>

Example 3: Actual use of await method by fetching json data


<script>
async function test(){
console.log("Message 2");
console.log("Message 3");
console.log("Message 4");
}
console.log("Message 1");
test();
console.log("Message 5");
output: Message 1
Message 2
Message 3
Message 4
Message 5

view video after 13 minutes

</script>

<!........................Advance Js - Symbols.............................!>
JS Datatypes:
String
Number
Boolean
Array
Object
Null
Undefined
Symbol

var x = "Hello world"; string


var x = 98; Number
var x = true; Boolean
var arr =["HTML","CSS","JS"]; Array
var obj = {first:"jane", last:"Doe"}; object
var x = null; Null
var x; undefined

symbol Data types:


assign value to variable x;
var x = Symbol(); // S must be capital of Symbol

var x = Symbol("Hello"); //unique value


// Hello is the identification of symbol or identifier.

var y = Symbol("Hello");
value of x and y variable are not same which is Hello.
if we compare them then we return false result.

if(x==y){
document.write("True");
console.log("True");
}else{
console.log("false");
}
output: false means these are unique.
if we want to use unique value in programming then we use symbols.
Practical Work:

in Head and Script tag :

Example 1:
let id= Symbol("Hello");
console.log(id); //Symbol(Hello)
console.log(typeof id);//symbol

Example 2:
Symbol Case: String Case:
let id1= Symbol("Hello"); let str1= "Hello";
let id2= Symbol("Hello"); let str2= "Hello";

console.log(id1 == id2); //false console.log(str1 == str2); //true

we cannot directly used in web document.

let id2= Symbol("Hello");


console.log(id2); Symbol(Hello)
alert(id2);//Uncaught TypeError: cannot convert a symbol value to a string.

if we use toString() method, then we can display symbol value in web document.
alert(id2.toString()); //convert symbol into string

if we use symbol method description it will return the value of symbol.


document.write(id2.description);//Hello

/////////////// How we use Symbol in Object

let age = Symbol();


let user = {
name : "ALi Raza",
class: 'BSCS',
//pass symbol in object
[age]: 25

};
console.log(user);
//output: {name: "ALi Raza", class: 'BSCS', Symbol(): 25}

Example 2:
let age = Symbol("Age");
let user = {
name : "ALi Raza",
class: 'BSCS',
[age]: 25

};
console.log(user);
//output: {name: "ALi Raza", class: 'BSCS', Symbol(Age): 25}

///////// if we define symbol outside the object.

let age = Symbol();


let user = {
name : "ALi Raza",
class: 'BSCS',
};

user[age] = 25;
console.log(user);
//output: {name: "ALi Raza", class: 'BSCS', Symbol(): 25}

if we want to display specific value, then use name with obj. like that
console.log(obj.value);
console.log(user.class);//BSCS
But we cannot display symbol value like above;
console.log(user.age);//undefined
To display symbole value you can use square barackets [];
console.log(user[age]);25

//////// we can use objects values with for in loop to display values.
if we use for in loop, then it will skip the value of symbol.

let age = Symbol("Age");


let user = {
name : "ALi Raza",
class: 'BSCS',
};

user[age] = 25;
user["gender"]="Male";

for(let key in user){


console.log(key);
}
output:
name
class
gender
skip the symbol value

/////// if convert object into json code and want to send to server, it will skip
////// the value of symbol.

if we want to change object into Json format then we use this function

JSON.stringify(obj-name);
console.log(JSON.stringify(user));{"name":"ALi
Raza","Class":"BSCS","gender":"Male"}
console.log(user);{"name":"ALi
Raza","Class":"BSCS","gender":"Male",Symbol(Age): 25}

if we want to send any Symbol value (in object) to Server then we must be
converted symbol into string.
//symbol is only used when we want to use unique value.

<!........................Advance Js - LOOPS.............................!>
LOOPS IN JS:
* while()
* do while
* for()
* for of()
* for in()
* foreeach()
* map()
* Iterators

Example:
var x = ["Apple","Orange","Grapes"];

symbol work with variable,objects.


iterators can be used with array, string or objects.
Iterators control the flow of array
Generator control the flow of function.

<!........................Advance Js - Iterators.............................!>
suppose we have one variable stored an array. like this

var x = ["Apple","Orange","Grapes"];

we want to read the values of variable one by one.

LOOPS IN JS:
* while()
* do while
* for()
* for of()
* for in()
* foreeach()
* map()
* Iterators

//we cannot control loops except Iterators.


suppose we run any loop, we can not stop it in mid. In iterator we can do it.

Example 1:

var x = ["Apple","Orange","Grapes"];
through loops , we can travel in array, first apple,second orange and then
Grapes.

for Loop:
for(let i=0; i<x.length; i++){
console.log(x[i]);//index of variable x.
}
for of Loop:
for(let x of values){
console.log(values);
}

Example 2:

var x = ["Apple","Orange","Grapes"];

Iterators syntax:
let y= x[Symbol.iterator]();//iteration and symbol is new data type
y.next(); //Apple
y.next(); //orange
y.next(); //grapes

we can use iterators with array, string or objects.

PRACTICLE:
implement in head tag with script tag.
<script>
let numbers = [100,200,300];
console.log(numbers);create array with index numbers.

let numbers = [100,200,300];


console.log(typeof numbers[Symbol.iterator]); returns function.

let iteration = numbers[Symbol.iterator](); // end me function paranthesis


console.log(iteration); //return arry iterator{}
console.log(iteration.next());//return value 100 from numbers.
done:false(means 100 k baad bhi koi value hye)
console.log(iteration.next());//return value 200 from numbers. done:false(means
200 k baad bhi koi value hye)
console.log(iteration.next()); //return value 300 from numbers. done:false(means
300 value hye)
console.log(iteration.next());//return value undefined from numbers. done:true

if we want to print specific value:

iteration.next();//100 but not print


iteration.next();//200 but not print
console.log(iteration.next());//return value 300 from numbers. done:false(means
300 value hye)
console.log(iteration.next().value); //300
console.log(iteration.next().done); //true

Example: we can use iterator in while loop

let num= [100,200,300,400,500];


let iteration = numbers[Symbol.iterator]();
let result = iteration.next();

while(!result.done){ //jab tak done ki value true nahi ho jati


console.log(result.value);//100
result=iteration.next();//in loop, second time 200, third time 300 and so on.
}

/////////////////iterator with string value with while loop

let str= "Abdul Manan";//we want to read each character of string

let iteration = str[Symbol.iterator]();


let result = iteration.next();

while(!result.done){ //jab tak done ki value true nahi ho jati


console.log(result.value);//A
result=iteration.next();//in loop, second time b, third time d and so on.

}
output:
A
b
d
u
l

M
a
n
a
n

/////////////////iterator with string value with for of loop

let str= "Abdul Manan";//we want to read each character of string

for(let char of str){


console.log(char);
}
output:
A
b
d
u
l

M
a
n
a
n
</script>

////////////////create itself iterator.

let numbers = [100,200,300,400,500];


let num = numberIterator(numbers); //create function
console.log(num.next());//first value 100 come
console.log(num.next());//second value 200 come
console.log(num.next());//third value 300 come
function numberIterator(arr){
var nextNum = 0;
return{
next(){//function
return{
value : arr[nextNum++]
done : false ;

}
}
}
}

///////////

function numberIterator(arr){
var nextNum = 0;
return{
next(){
if(nextNum < arr.length){
return{
value : arr[nextNum++]
done : false ;
}
}else{
return{
done : true;

}
}
}
}
}

let numbers = [100,200,300,400,500];


let num = numberIterator(numbers); //create function
console.log(num.next());//first value 100 come
num.next(); not print 200
console.log(num.next().value);//300
console.log(num.next());//fourth value 400 come
console.log(num.next().value);//500 come
console.log(num.next());// done : true
<!........................Advance Js - Generators.............................!>

Iterators control the flow of array


Generator control the flow of function.
if we want to display specific portion from function then we can use generator.

Example:

function test(){
console.log("First");
console.log("Second");
console.log("Third");
}
test(); // output: First,Second,Third

Example 1: use sterisk (*) with function name to apply Generator


to control over the statements. use yield keyword: yield mean Pause.
function *test(){
yield "First";
yield "Second";
yield "Third";
}
call generator function

let g =test();
g.next(); return First
g.next(); return Second
g.next(); return Third

Practical Work:

function generator(){
console.log('First Message');
console.log('Second Message');
}
generator();
output: First Message, Second Message

;;;;;;;;;;;;;By making generator function:

function *generator(){
console.log('First Message');
console.log('Second Message');
}
let g = generator();
console.log(g);
output://///// generateit{<suspendid>}, when open it, it will show methods of
generator like next(),return(), throw()

these methods are mostly used. most common used method is next()
Example 1:
<head><script>
function *generator(){
console.log('First Message');
console.log('Second Message');
}
let g = generator();
console.log(g.next());
output: First Message
Second Message
{value: undefined, done:true}
</script></head>

Example 2:
<head><script>
function *generator(){
console.log('First Message');
yield 'Yield No. 1'; //here is code pause
console.log('Second Message');
yield 'Yield No. 2';
}
let g = generator();
console.log(g.next());
output: First Message
{value: "Yield No. 1", done:false}//false means function me or bhi values present
hye jab wo finishied ho jaye gi tab done jo hy wo true ho jaye ga.
</script></head>

Example 3:
<head><script>
function *generator(){
console.log('First Message');
yield 'Yield No. 1'; //here is code pause
console.log('Second Message');
yield 'Yield No. 2';
}
let g = generator();
console.log(g.next());
console.log(g.next());
output: First Message
{value: "Yield No. 1", done:false}
second Message
{value: "Yield No. 2", done:false}

console.log(g.next());
{value: undefined, done:true}
</script></head>

Example 4:
<head><script>
function *generator(){
yield 'Yield No. 1'; //here is code pause
yield 'Yield No. 2';
yield 'Yield No. 3';
}
let g = generator();
console.log(g.next());
g.next();
console.log(g.next().value);
output:
{value: "Yield No. 1", done:false}
Yield No. 3
{value: undefined, done:true}
</script></head>

Example 5:
//////////////if we have multiple Yields then we can use for of loop.
<head><script>
function *generator(){
yield 'Yield No. 1';
yield 'Yield No. 2';
yield 'Yield No. 3';
}
let g = generator();
for(let value of g){
console.log(value);
}

output:
Yield No. 1
Yield No. 2
Yield No. 3

</script></head>

Example 6:
//////////////if we have multiple values in function then we can use while loop.
<head><script>
function *generator(){
let nextNum = 100;
while(true){
yield(nextNum++);
}
}
let g = generator();
console.log(g.next()); //return 100 first time
console.log(g.next()); //return 101 second time
console.log(g.next()); //return 102 third time and so on.
console.log(g.next().value);
console.log(g.next().value);
console.log(g.next().value);

output:
{value: 100 , done:false}
{value: 101 , done:false}
{value: 102 , done:false}
103
104
105
</script></head>

Example 7:
//////////////if we have multiple Yields then we can use for of loop.
<head><script>
function *generator(){
let nextNum = 100;
while(true){
yield(nextNum++);
}
}
let g = generator();//if we run this without if statment then undefined
time printing.
for(let value of g){
if(value > 119) break;
console.log(value);
}

output:
100
101
.
.
.
119

</script></head>

Example 7:
//////////////Another method to use Yield
<head><script>
function *generator(){
let result = yield;
console.log(`Result : ${result}`); //print result value from next();
}
let g = generator();
g.next();
g.next(500); send to yield

output:
Result : 500

</script></head>

Example 8: we can also multiply any number with yield, and we can send multip
values by creating array of yield;

//////////////Another method to use Yield


<head><script>
function *generator(){
let yarray= [yield,yield,yield];
console.log(`Result : ${yarray}`);
}
let g = generator();
g.next();
g.next(500); send to yield array
g.next(600); send to yield array
g.next(700); send to yield array
g.next(800); send to yield array

output:
Result : 5000,6000,7000
if we want to display specific vlaue from array then gives index number with
array variable. like that

function *generator(){
let yarray= [yield,yield,yield];
console.log(`Result : ${yarray[2]}`);
}
let g = generator();
g.next();
g.next(500); send to yield array
g.next(600); send to yield array
g.next(700); send to yield array
g.next(800); send to yield array

you can also pass string vlaues or any other value:


g.next("PHP"); send to yield array
g.next("Python"); send to yield array
g.next("Java"); send to yield array
g.next(800); send to yield array

output:
Result : 7000
Result : Java
</script></head>

Example 9: Take Two values of Yield: single value and an Array.


<head><script>
function *generator(){
yield 55;
yield ['Node','Angular','React'];
}
let g = generator();
console.log(g.next());
console.log(g.next());

output:
{value: 55, done:false}
{value: Array(3), done:false} // gives values of array by index numbers.
</script></head>

Example 10: display each value of array separatley use * with yield array.
<head><script>
function *generator(){
yield 55;
yield* ['Node','Angular','React'];
}
let g = generator();
console.log(g.next().value);
console.log(g.next().value);
console.log(g.next().value);
console.log(g.next().value);
console.log(g.next().value);

output:
55
Node
Angular
React
undefined

Example 11: use spread operator with yield


<head><script>
function *generator(){
yield 'php';
yield 'Node';
yield 'Angular';
yield 'React';
}
let g = generator();
console.log(g.next().value);
console.log(g.next().value);
console.log(...g);

output:
php
Node
(2) ["Angular","React"]

Example 12: return method of yield


//return are used when we end the function in between the working,
then we can use return method
<head><script>
function *generator(){
yield 'php';
yield 'Node';
yield 'Angular';
yield 'React';
}
let g = generator();
console.log(g.next().value);
console.log(g.return('Ending Now'));
console.log(g.next().value);

output:
php
{value : "Ending Now", done:true}//true means values are finished
undefined

<!........................Advance Js - Strict Mode.............................!>

strict mode check syntax error.

a=10;
console.log(a);//print 10

if we use strict mode.

"use strict";
a=10;
console.log(a);
output will be:
//a is not defined or declared.

Function:
"use strict";
function test(){
let a=10;
}
test(); //print 10

function test(){
"use strict";
b=10;
}
test(); //Reference Error, b is not defined or declare at test
function.

passing parameters to a function:


FIRST:
<script>

funtion test(a,b,b){
console.log(a + b + b);

}
test(10,20,30); // output will be 70 it is wrong when we not used
strict mode.
</script>

SECOND:
<script>
"use strict";

funtion test(a,b,b){
console.log(a + b + b);

}
test(10,20,30); // Syntax error occur:Duplicate parameter name not
allowed when we used strict mode.
</script>

THIRD:
<script>
"use strict";

funtion test(a,b,c){
console.log(a + b + c);

}
test(10,20,30); // output will be 60 it is true when we used strict
mode.
</script>
<!........................Advance JavaScript - Error
Handling.............................!>

We use try....catch method for error handling.


work synchroneously, if we used setTimeout() function then try...catch not work
properly. we can use try...catch in setTimeout functions.

try{
//some code goes here...when code successful
}catch(){

//when any error comes in try code.


}

Example:

try{
console.log('start of try');
jkdhfkdjsl;

console.log('End of try');
}catch(){

console.log('Error has occured.');


}
output:
//start of try
//error has occured as jkdhfkdjsl; when error occur on any line then
catch function will called automatically as above.

Passing variables to catch method:


try{
console.log('start of try');
jkdhfkdjsl;

console.log('End of try');
}catch(error){ //mistakes store in error variable

console.log(error);
}
output will be:
//start of try
//ReferenceError:jkdhfkdjsl is not defined. and tell line number.

work synchroneously, if we used setTimeout() function then try...catch not work


properly.

try{
setTimeout(function(){
blabla;

},1000)
}catch(error){

console.log(error);
}

we can use try...catch method inside the setTimeout function. like this,

setTimeout(function(){
try{
blabla;
}catch(error){
console.log("error has occured");
}

}, 1000);//after 1 second display 'error has occured'.

Display error separately: like name,message and stack(both name + message)


<script>
try{
blabla;
}catch(error){
console.log(error.name);//ReferenceError
console.log(error.message);//blabla is not defined
console.log(error.stack);//ReferenceError: blabla is not defined at
error-handling.html:8
above 8 is line
number.
//only one bhi display kar sakty hye.like below
console.log(error.message);
}
</script>

7 Different types of errors in javascript:


* EvalError //come when we use Eval() name function.not important
* RangeError //when we use type=range in HTML then we use this
function.
* ReferenceError //Reference error come when we use variable or function
which is not defined or declared in JS.
* SyntaxError //come in large number of time. like in
loops(for,while,do-while,for of,foreach etc) or statments(if,if else,if else
if,switch etc)
* TypeError //come in variable assign values.
* URIError //come in URL parameters. spelling mistake or worng method
of writing.
* AggregateError //use in promises.

<script>
try{
blabla;
}catch(error){

if(error instanceof ReferenceError){


console.log('Reference Error');
}
else if(error instanceof TypeError){
console.log('Type Error');
}
else{
console.log('Unknown Error');
}

}//ReferenceError
</script>

Where to use try...catch method Mostly.


when we fetch or send data from server then use try..catch

try{
let json = '{"name":"Yahoo Baba" , "age":30}';
let user = JSON.parse(json);//pass variable json which contain name and
age variable.
related to json in javascript two methods are json.parse and json.stringify
if we want to convert server data into js object then use JSON.parse
if we want to send javascript code into server then convert js code into json then
we use stringify
//JSON.Parse convert json data into javascript
objects.
//JSON.stringify convert javascript object into json
data.

}catch(error){
console.log(error);
}

use if statement in json...try

<script>
try{
let json = '{"name":"Yahoo Baba" , "age":30}';
let user = JSON.parse(json);
if(!user.name){
throw new Error("Incomplete Data : No Name");

}
console.log(user.name);
console.log(user.age);

}catch(error){
console.log(error);
}
//Yahoo Baba
//30

</script>
if we miss out any variable of json like that name missing

<script>
try{
let json = '{ "age":30}';
let user = JSON.parse(json);
if(!user.name){
throw new Error("Incomplete Data : No Name");

}
console.log(user.name);
console.log(user.age);

}catch(error){
console.log(error);
}
//Error: Incomplete data : No name

</script>

finally method is optional when we used try...catch method:


two possibities:
when error come in try method then catch method run first and then finally method
runs
when no error in try method then try method run before and after that finally
method run.
means both time finally method run in the case of true or false of try.

if error occur in try method:


<script>
try{
let json = '{"age":30}';
let user = JSON.parse(json);
if(!user.name){
throw new Error("Incomplete Data : No Name");

}
console.log(user.name);
console.log(user.age);

}catch(error){
console.log(error);
}finally{
console.log('Finally');
}

output will be:


//Error: Incomplete Data : No Name
//Finally
</script>

if error not occur in try method:


<script>
try{
let json = '{"name":"abdul Manan", "age":30}';
let user = JSON.parse(json);
if(!user.name){
throw new Error("Incomplete Data : No Name");

}
console.log(user.name);
console.log(user.age);

}catch(error){
console.log(error);
}finally{
console.log('Finally all went gone');
}

output will be:


//abdul Manan
//30
//Finally all went gone
</script>

You might also like