Advanced Js
Advanced Js
>
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)
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";
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)
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);
Example 2:
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
What is this?
In JavaScript, the this keyword refers to an object.
<!........................Advance Js - Template
Strings.............................!>
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.
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();
Before
let welcome = function(name){
return `Welcome ${name}`;
}
console.log(welcome("Yahoo Baba"));
After
console.log(welcome("Yahoo Baba"));
// sum only two arguments if 3 or 4 arguments are come then an error occured.
Solution:
function sum(){
let sum=0;
// if we pass one string and one integer value then above function failed. so rest
operator is used for this problem
let sum = 0;
for(let i in args){
sum += args[i];
}
document.write(sum);
}
sum("Yahoo Baba",10,20,30,40,50);
let sum = 0;
for(let i in args){
sum += args[i];
}
document.write(sum);
}
/////////simple example
<!........................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.
}
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);
let sum = 0;
for(let i in args){
sum += args[i];
}
document.write(sum);
}
console.log(...arr);
output: 1,2,3,4
var obj1 = {
name : "Yahoo Baba",
course : "Btech"
}
var obj2 = {
age : 25
}
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
var obj = {
name,
course
};
console.log(obj);
console.log(obj.name);
JavaScript
var obj = {
[n] : "Yahoo Baba",
course : "Btech",
detail(){
return `${this.name} is student of ${this.course}`;
}
};
JavaScript
var obj = {
[name + "name"] : "Yahoo Baba",
course : "Btech",
detail(){
return `${this.studentname} is student of ${this.course}`;
}
};
JavaScript
console.log(obj.detail());
JavaScript
console.log(obj.detail());
console.log(s.fullname);
console.log(s.course);
<!........................Advance Js - Destructuring
Array.............................!>
let user = ["Yahoo Baba", 25, "Delhi"];
let[name,age] = user;
console.log(name);
console.log(age);
console.log(city);
console.log(gender);
console.log(salary);
JavaScript
console.log(name);
console.log(args);
JavaScript
console.log(city);
<!........................Advance Js - Destructuring
Object.............................!>
let user = {
name : "Yahoo Baba",
age : 25,
city : "Delhi"
}
console.log(city);
JavaScript
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.
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.
console.log(typeof a);
a.message();
//here a is the object calling a function named as message.
constructor(){
console.log("Constructor Function");
}
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");
}
Initilize Property
class student{
constructor(){
let studentname;
}
}
Prototype method
class student{
constructor(name){
this.studentname = name;
}
hello(){
console.log("Hello " + this.studentname);// this keyword represent studentname
of
of current class.
}
}
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
}
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");
}
}
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>`)
}
}
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>`)
}
}
a.info();
//b.info();
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.
Practical Work:
Folder name:modules
file name:index.html, library.js like file1.js and main.js like file2.js
//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
// 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};
export { user };
//for class
let a=new test();
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.
Pending
Fulfilled
Rejected
});
}
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);
}
/////////////////////////////////////////////
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.
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
Example 2:
<script>
function prom(complete){
</script>
<script>
function prom(complete){
prom(true).then(onfulfilment );
prom(true).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){
//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);
});
</script>
Example 6:
<script>
function prom(complete){
//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);
});
</script>
Example 7:
passing two variable value and divide them.
<script>
function prom(a,b){
//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);
});
prom(5,0).then((result) => {
console.log(result);
}).catch((error) => {
console.log(error);
});
//error occured: Failed to calculate
</script>
<!........................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]).then().catch();
What is Promise.all()?
promise.all() function check all or multiple promises by variable name.
//Promise.all([p1,p2]);
Promise Syntax:
1st Promise:
Promise.all([p1,p2]);
<script>
### first promise
},1*1000);
},2*1000);
},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>
},1*1000);
},2*1000);
},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
},1*1000);
},2*1000);
},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
},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
},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.............................!>
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
Syntax of AJAX?
};
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){
xhttp.open('GET',"readme.txt",true)
xhttp.send();
}
</script>
</body>
// fake json data (search on google for fake data)
//JavaScript
XMLHttpRequest
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.
Two files:
readme.txt
Hello this is text file
index.html
<script>
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.
Example 1:
<script>
async function test(){
return "HELLO";
}
console.log(test());
output:HELLO
</script>
</script>
test().then(result() =>{
console.log(result);
});
output: HELLO
</script>
</script>
test().then(result() =>{
console.log(result);
});
output: HELLO
</script>
Await Method:
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>
</script>
</script>
<!........................Advance Js - Symbols.............................!>
JS Datatypes:
String
Number
Boolean
Array
Object
Null
Undefined
Symbol
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:
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";
if we use toString() method, then we can display symbol value in web document.
alert(id2.toString()); //convert symbol into string
};
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}
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.
user[age] = 25;
user["gender"]="Male";
/////// 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"];
<!........................Advance Js - Iterators.............................!>
suppose we have one variable stored an array. like this
var x = ["Apple","Orange","Grapes"];
LOOPS IN JS:
* while()
* do while
* for()
* for of()
* for in()
* foreeach()
* map()
* Iterators
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
PRACTICLE:
implement in head tag with script tag.
<script>
let numbers = [100,200,300];
console.log(numbers);create array with index numbers.
}
output:
A
b
d
u
l
M
a
n
a
n
M
a
n
a
n
</script>
}
}
}
}
///////////
function numberIterator(arr){
var nextNum = 0;
return{
next(){
if(nextNum < arr.length){
return{
value : arr[nextNum++]
done : false ;
}
}else{
return{
done : true;
}
}
}
}
}
Example:
function test(){
console.log("First");
console.log("Second");
console.log("Third");
}
test(); // output: First,Second,Third
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
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;
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
output:
Result : 7000
Result : Java
</script></head>
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
output:
php
Node
(2) ["Angular","React"]
output:
php
{value : "Ending Now", done:true}//true means values are finished
undefined
a=10;
console.log(a);//print 10
"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.
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.............................!>
try{
//some code goes here...when code successful
}catch(){
Example:
try{
console.log('start of try');
jkdhfkdjsl;
console.log('End of try');
}catch(){
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.
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");
}
<script>
try{
blabla;
}catch(error){
}//ReferenceError
</script>
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);
}
<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>
}
console.log(user.name);
console.log(user.age);
}catch(error){
console.log(error);
}finally{
console.log('Finally');
}
}
console.log(user.name);
console.log(user.age);
}catch(error){
console.log(error);
}finally{
console.log('Finally all went gone');
}