JAVASCRIPT INFO
Switch Statement
1. In switch statement the equality check is always strict.
let arg = prompt("Enter a value?");
switch (arg) {
case '0':
case '1':
alert( 'One or zero' );
break;
case '2':
alert( 'Two' );
break;
case 3: //this wonty be executed as prompt returns a string
alert( 'Never executes!' );
break;
default:
alert( 'An unknown value' );
}
2. Functions - Global variable reassignment inside a function will override the
global variable
let userName = 'John';
function showMessage() {
userName = "Bob"; // (1) changed the outer variable
let message = 'Hello, ' + userName;
alert(message);
}
alert( userName ); // John before the function call
showMessage();
alert( userName ); // Bob, the value was modified by the function
3. Function - Global variable re declaration inside a function.
The local variable is created which shadows the global variable only
within the function
let userName = 'John';
function showMessage() {
let userName = "Bob"; // (1) changed the outer variable
let message = 'Hello, ' + userName;
alert(message);
}
alert( userName ); // John before the function call
showMessage();
alert( userName ); // John
4. The Function Parameter gets the copy of the value from the arguments. So it does
not modify the outside value.
Values passed to a function as parameters are copied to its local variables.
function showMessage(from, text) {
from = '*' + from + '*'; // make "from" look nicer
alert( from + ': ' + text );
}
let from = "Ann";
showMessage(from, "Hello"); // *Ann*: Hello
// the value of "from" is the same, the function modified a local copy
alert( from ); // Ann
5. DEFAULT PARAMETER -
** In a function if the argument is not passed corresponding to a value then it is
undefined.
function init(data1,data2){
[Link](data1,data2)
}
init(1) //1 undefined
** default parameter can also be a function
6. RETURN VALUE
** If the function does not return anything then it will return undefined.
function sum(a, b) {
return;
}
let result = sum(1, 2); //undefined
7. FUNCTION in javascript is a VALUE. We can store it in a variable or pass it as a
value to another function.
8. Variables in javascript are dynamically typed that is same variable can hold
different data types.
We have typescript which is a superset of javascript which adds static typing to
the language.
9. Property name shorthand
function userDetails(name,tech){
return {
name: name,
tech : tech
}
}
userDetails('Rajat', 'React JS')
The above can be rewritten as \
function makeUser(name, age) {
return {
name: name,
age: age,
// ...other properties
};
}
let user = makeUser("John", 30);
alert([Link]); // John
10. Object 'in' operator
let obj = {
name : 'Joe',
tech : 'React'
}
alert('name' in obj); //true
alert('age' in obj); //false
11. Sorting with 'in' operator
When we are using INTEGER PROPERTY as keys sorting of keys happen in a ascending
order.
Else it will just follow the order in which items are declared.
The “integer property” term here means a string that can be converted to-and-from
an integer without a change.
alert( String([Link](Number("49"))) ); // "49", same, integer property
alert( String([Link](Number("+49"))) ); // "49", not same "+49" ⇒ not integer
property
alert( String([Link](Number("1.2"))) ); // "1", not same "1.2" ⇒ not integer
property
let obj = {
91 : 'India',
1: 'USA',
12: 'Australia',
10: 'South Africa'
}
for(let key in obj){
[Link](key); // 1 10 12 91
}
12. COPY OF OBECT IN JS
In JS when we store an object in a variable we are not directly storing the object
but the refernce of the object.
This refernce will point to the address of the object in the memory.
When an object is copied, the object stored in the memory is not copied only
the refrence of the object is copied.
** COPYING AN OBJECT CREATES ONE MORE REFRENCE OF THE SAME OBJECT
13. CLONING AN OBJECT - This will result in creating a new object with a different
refernce.
1st method: Using for loop
let obj1 = {
tech1 : "react",
tech2: 'Javascript'
}
let obj2 = {};
for(let key in obj1){
obj2[key] = obj1[key]
}
2nd method: [Link]()
3rd method : Spread Operator
14. Objects inside a Nested Object are also copied by refrence.
SO the cloned object will have the same refernce as the orginal for the nested part
of it.
const obj1 = {
name : 'Test Data',
year: '2016',
specs : {
spec1: 'react',
spec2: 'javascript'
}
}
const obj2 = {}
for(let key in obj1){
obj2[key] = obj1[key]; //Here [Link] === [Link] which are the same
as objects are copied by refrence.
}
15. DEEP CLONE (ALSO KNOWN AS STRUCTURED CLONING)
1. Using the structuredClone method
const obj1 = {....}
const obj2 = structuredClone(obj1);
2. Using _cloneDeep from javascript library lodash
16. Constructor functions are used to create many similar objects.
function User(name){
[Link] = name;
[Link] = 'India';
}
const user1 = new User('Rajat'); //new keyword is used to create a new object
[Link](user1);
const user2 = new User('Test2');
[Link](user2);
17. Usyually CONSTRUCTOR functions do not have a return statement. They write
everything into the this keyword.
18. OPTIONAL CHAINING: It is a safe way to access nested object properties , even
if an intermidiate property doea not exists.
Using optional chaining we get the result as undefined instaed of an error.
let res={};
// alert([Link]); //undefined
// alert([Link]) //type error: cannot read properties of undefined
alert(res?.address?.street); //Using optional chnaining will return undefined
instaed of error message
--The ? syntax makes the value before it as optional
--Optional chaining are usew for values which could be optional
--user?.address -- Here usewr can be optional
--Optional chaining short circuits if a null or undefined value is found
1. obj?.prop – returns [Link] if obj exists, otherwise undefined.
2. obj?.[prop] – returns obj[prop] if obj exists, otherwise undefined.
3. [Link]?.() – calls [Link]() if [Link] exists, otherwise returns
undefined
19. Object property keys are always string. so obj[1] is obj["1"] or obj[true] is
obj["true"}
20. Symbol : Symbols are PRIMITIVE type of UNIQUE identifiers.
let id1 = Symbol("id"); //id is the description of the symbol
let id2 = Symbol("id");
[Link](id1 == id2); //false
21. Symbols do not auto convert to string.
let id = Symbol("id");
alert(id); // TypeError: Cannot convert a Symbol value to a string
alert([Link]()) //Symbol(id)
alert([Link]) //"id"
22. Symbols allows us to create hidden properties that no part of the code can
access or override.
//Using symbols as properties we cannot override them , whereas using string as
properties we can override them.
const user = {
name: 'rajat'
}
const id = Symbol("id");
user[id] = 1;
const id2 = Symbol("second id");
user[id2] = 2;
let id3;
user["id3"] = 3;
user.id3 = 4;
[Link](user)
23. Symbols are ignored in the for in loop. [Link]() also ignore them.
const id = Symbol("id")
const user = {
name: 'Rajat',
[id] : 21,
props: 'React'
}
for(let key in user){
[Link](key) //name props
}
24. Global Symbols:
let id = [Link]("id")
let id2 = [Link]("id")
id == id2 //true
25. let obj = {name : 'Rajat'}
alert(obj) //[object Object] it is the string representation of the object
9. LINTERS are tools which can automatically check the style of your code and make
improving suggestions.
They can also help in idenifyig bugs like typos in variable names and
functions.
ESLint , JSLint, JSHInt
Monday
DATA TYPES STRINGS
1, length property
--> 'test\n'.length = 5
--> ' .length = 0
2. at() Method - It is used to get a character at a position
'test'.at(2) = 's'
'[Link](-1) = 't'
'test'[2] = 's'
'test'[0] = undefined
3. STRINGS IN JAVASCRIPT IS IMMUTABLE
eg. const str = 'rajat';
str[0] = 't' //This wont work
[Link]() , toLowerCase()
5. SEARCHING A SUBSTRING
There are multiple ways to look for a substring within a string
indexOf(substr'position) //indexOf returns the index of the substring
let str = 'Widget with id');
[Link]('id') //1
[Link]('id'2) //12
[Link]('sid') //-1 //This can be used to check if an substring is part
of an string
includes(substr,position)
let str = 'Widget with id');
[Link]('id') //true
[Link]('sid') //false
6. Getting a substring
slice(start position , [,end]) - end is optional and its sunstring is not
included
let str = "stringify"
[Link]() //stringify
[Link](1,5) //trin
[Link](1) //tringify
[Link](-4,-1) //gif
[Link](3,1) // '' start cannot be greater then the end in SLICE method
substring(start,end) : S
1. Same as slice but supports end value to be less then the start value.
2. Do not support -ve values. -ve vealues are treated as zero
let str = "stringify"
[Link](4,1) //tri Internally it swaps the two values
[Link](-1,-2) // '' negative values are not supported they mean 0
str,substring(-1) = stringify . Internally this will become zero(0)
[Link](start,length) //In substr we speciofy length as the second argument
[Link](0,4) //stri
'a' > 'A' //true This is because strings in javascript are encoded using UTF-
16. In UTF-16 a isd 97 and A is 90.
ARRAYS..........Arrays are special type of objects used to store ordered
collections.
1. Arrays are mutable.
const arra = [1,2,3,4,5]
arra[0]=10
arra = [10,2,3,4,5]
2. Accessing the last element in the array
const arra = [1,2,3,4,5]
arra[-1] //undefined because -1 is treated as an array index
arra[[Link]-1] //5
[Link](-1) //5
3. Array as queue - FIFO - push and shift
Array as stack - LIFO - push pop
pop() - removes the last element from the array and returns it
push() - add an element to the end of the array and returns its length of the
array
shift() - removes the first element of the array and returns it
unshift() - adds an element to the beginning of the array and returns the
length of the array
4. During copying and cloning arrays work like object. They are copied by
reference.
5. for..in should be used with obects and for of should be used with arrays.
6. length property The length property adds an one to the last index.
const arra=[];
arra[123] = 'test'
arra,length =123+1 =124
7. let arra = [1,2,3,4,5]
[Link] = 2; //length will mutate the original array
arra =[1,2]
8. Emptying the array : arra,length =0;
9. let arra = new Array(2) // This will cvreate an empty array withy length as 2.
10. toString() - Arrays do have their own implementation of the toString() method.
[].toString() = ''
[] + 1 ='1'
[1]+1 ='11'
[1,2] + 1 = '1,21'
11. Array Comparision
1. [1,2] == [1,2] //false becausew they are pointing to different arrays in
the memory
2. [] == 0 //true becauise with type coersion [] is converted to 0
3. [] == '' //true because with type coersion empty array is converted to
''
12. ARRAY METHODS:
---> ADDING?REMOVING ITEMS IN AN ARRAY
1. push()
[Link]()
[Link]()
4. unshift()
5. splice --> splice(startIndex, deleteCount, addElement1, addElement2,
addElementn)
[1,2,3].splice(0,1) = [1] //splice returns the array of removed elements
[1,2,3].splice() = []
[1,2,3].splice(0,0,12,13] = [12,13,1,2,3] //we can use splice just to adfd
elements wityhout removing anuy elements.
[1,2,3].splice(-1,2) = [3] //This is because it will remove three elements
staring for index -1.
6. slice --Slice method does not mutate the original array.
-- Creating a copy using the slice method creates a new array with a
new reference.
-- const arra = [1,2,3,4,5]
const newArra = [Link]()
arra = newArra //false
7. concat --Concat method does not mutate the original array.
Concat copies the elements of the array.
const arra = [1,2,3,4,5];
1. [Link]([10,20],[30,40]) =
[1,2,3,4,5,10,20,30,40] //elements are copied in concat
2. [Link]([10,20],30,40) - same result as above
3. [Link]([10,20],[30,[40,50]]) - [1,2,3,4,5,10,20,30,
[40,50]]
8. forEach - forEach method allows us to run a function on each element of the
array.
It returns undefined.
--SEARCHING IN AN ARRAY
[Link](value, startingPoint) - returns index of the value. If not found returns
-1 //indexOf uses strict equality
[Link]() - starts the checking of the index from end
3 includes(value,startingPooint) - returns true if value is present.
--const arra = [NaN]
[Link](NaN) = true
[Link](NaN) = -1
4. find() - It helps us to find an array from the array of objects. If returns the
item it found if not it returns undefined.
let arra = [1,2,3,4,5]
[Link]((item,index,array) => item === 1) //returns item if not found found
returns undefined
[Link]()/findLastIndexOf() :
let arra = [1,2,3,4,5];
[Link]((item,index,array) => item ==2) //returns index of the item if
not found -1.
5. filter() - find() method returns a single element whereas the filter method
returns an array of matching elements
--TRANSFORM AN ARRAY
[Link] method - The map method runs a function on each element of the array and
returns an updated array.
--Difference between map and filter methods
let users = [
{id: 1, name: "John"},
{id: 2, name: "Pete"},
{id: 3, name: "Mary"}
];
[Link](item=> [Link] <3) //[ {id: 1, name: "John"}, {id: 2, name:
"Pete"}]
[Link](item=> [Link] <3) // [true true false] //map method does not filter
out any items. If we are checking a condiotion in map it will return boolean of
arrays.
2. SORT method: Sort method MUTATES the original array.
We have a toSorted method which does not mutate the
original array.
In the sort method the items are sorted by string by
default in ascending order.
const arra = [1,2,15,115];
[Link]() // [1,15,115,2]
//Compare Function --We need a compare function to sort in in the order in
whioch we want.
function compare(a,b){
if(a>b) return ;
if(a<b) return -1;
if(a ===b) return 0;
}
[Link](compareFunction) // [1,2,15,115]
3. REVERSE METHOD : Reverses the array. It mutates the original array.
we have a toReversed method which does not
mutate the original array
4. Split(delimiter) and Join(glue)
5. REDUCE METHOD : The result of the previous function call becomes the first
argument.
6. ReduceRight Method : Reduce right is same as reduce but the function runs from
right to left.
--------------------------
Array Check: [Link]()
7. Some method : It returns true if one of the value matches the conditions passed
in the callback function. It is same asd OR operator.
8. Every method : It returns true if all the values matches the conditions passed
in the callback function. It is same as AND operator.
//Comparing two arrays using every method - (This cannot be used to compare nested
arrays)
const arra1 = [1,2,3,4,5];
const arra2 = [1,2,3,4,5];
[Link]((item,index)=> item ==== arra2[index)) //true
9. flat() and flatMap() - cover these apter completeing Sets and Maps
===================================================
10. MAPS and SETS
Objects are used for storing keyed collection.
Arrays are used for storing ordered collection.
Maps are used for storing keyed data collections just like object. Maps and
Objects are used to store key value pairs
The difference is that map allows keys of any data types. (String,
Number,Boolean,Objects)
In objects keys are converte to string but in maps this does not happen.
const map = new Map();
[Link](1,'value1')
[Link]('2',,'value2')
[Link](true,'value3')
[Link](1) //'value1'
[Link] //3
[Link]('2') // true
[Link](1) //true
[Link]() //removes all the elements of the array
--Using map[key] will treat the map as a regular object. We should avoid that.
--Using objects as keys is one of the most important fetaure of using a map.
let data = {name : 'Test1'}
let user1 = new Map();
[Link](data, 124);
--When using an object as a key in an Object it will convert it to a string [object
Object]
--let data = new Map([
['tech1', 200],
['tech2',300],
['tech3',300],
]);
[Link]() --> Returns an array of keys
[Link]() and --> Returns an array of values
[Link]() are used to iterate over a map. - returns an Array of key-value
pairs from an object
//In Maps the instertion order is maintained when we are outputing the result
--Creating MAP from an OBJECT - [Link]()
1. const obj = { name: 'test' , data: 10 }
const map = new Map([Link](obj))
--Creating OBJECT FROM AN ARRAY - [Link]()
const arra = [[1,'test'],[2,'test2'],[3,'test3]]
const obj = [Link](arra) //{1: 'test', 2: 'test2' , 3: 'test3'}
11. SETS - Sets are special type of collection in javascript where each value will
occur only once.
const set = new Set();
[Link](10)
[Link]() //wil;l return true if value exits
[Link] // size is a property like length
[Link](10) //true
12. Weak Map and Weak Set
let obj = {name : 'test data'}
obj = null //This will remove the object from the memory
But if the object obj is added as an element or key of a array or map it can still
be accessed.
let arra = [obj];
obj =null;
arra[0] = obj
But if we have a Weak Map instead of a Map in the above scenario then it the
object once removed from the memory will not be accessibl
13. keys() , values() and entries() have different syntax for object and map.
[Link]() , [Link]()
[Link]() , [Link]()
14. Use of [Link](0 and [Link]()
const obj = {'react': 1 , 'javascript':2 , 'typescript':3} //Docuble the values
[Link](obj) = [[react,1],[javascript,2],[typescript,3]]
let res =[Link](obj).map(item => [item[0], item[1] *2]
[Link](res) //This will update the back to an object from an array
--DESTRUCTURING:: Internally destructuring assignment works by iterating over the
values in the right. Destructuring is like a syntatic sugar for "for...of".
let [a,b,c] = "abc";
--In object destructuring the order on the left hand side does not matter.
let options = {
title: 'test',
width: 100,
height: 200
}
let {height,title,width} = options; //height = 200, etc etc
typeof [Link](obj) is an string
=================================
=========FUNCTIONS IN JAVASCRIPT====== Functions in javascript are values
1. recursion is when we are calling the function itself.
eg. Normal function
function normal(x,n){
let res=1;
for(let i=0;i<n;i++){
res = res * x;}
return res;
}
normal(2,3)
Recusrive function
function recursive(x,n){
if(n==1) { return x}
else { return x * recusrive(x,n-1)}
2. Execution Context is a internal data structure that contains details about the
execution of the function. One function call has one execution context.
3. HOSITING : Variable declararions are hoisted and not the assignment.
eg: function sayHi() {
alert(phrase); //undefined as the declaration is hoisted and not the assignment
var phrase = "Hello";
}
sayHi();
4. We use IIFE to make functions declared with var as block scoped.
5. Global Object : In the browser the global object is called the window. In Node
JS it is called global.
recently a common name globalThis was added for
gloabl object in all environments
The Global Object includes the window height [Link] and
[Link]
6. Function Properties:
1. name property: It returns the name of the function
function res(){
return 'demo'
)
//rest,name = 'rest'
2. length property: It returns the number of function parameters
function test(a,b,c){
[Link]([Link]) //3
}
function test(a,b,c,...rest){
[Link]([Link]) //3
}
//Function declarations are hoisted before variable declarations.
So if we have a variable and a function with the same name, the variable
declaration will override the function as it is hoisted later on.
//new Function('a','b','return a+b')
function getFunc(){
let value = "test";
let func = new Function('alert(value)');
return func;
}
getFunc()() //error . Function created with new function will not have access to
the lexical environment. It has access directly to the global scope.
==============setTimeout and setInterval======================
1. setTimeout will run only once after the time expires whereas aetInterval will
run after continuous intervals.
let timerID = setInterval(()=> alert('tick'),2000);
setTimeout(()=> {
clearInterval(timerID); //we can use clearInterval() inside setTimeout as it
is called only once.
alert('Stop')
},6000)
2. Nested setTimeout allows us to set the delay between the executions more
precisely than setInterval.
let i = 1;
setInterval(function() {
func(i++);
}, 100);
let i = 1;
setTimeout(function run() {
func(i++);
setTimeout(run, 100);
}, 100);
[Link] collection of setTimeout and SetInterval
When a function is passed to settimeout or setInterval, an iternal reference is
created to it and saved in the scheduler.
It prevents the function from being garbage collected, even if there are no other
references to it.
It will stay in the memory until we call setInterval or setTimeout.
4. Zero delay setTimeout
setTimeout(()=> alert('test'));
alert('testing') //testing test
//Even when the delay is 0 , the setTimeout() will execute only after the stricpt
has completed execution.
//Print numbers afetr equal intervals
function printNumbers(from,to){
let current = to;
let timerID = setInterval(()=> {
alert(current);
if(current == to){
clearInterval(timerID)
}
current++;
},1000)
}
printNumbers(2,10)
==============Function Binding=================
1. let user = { name " 'test'}
function details(){
alert([Link]) //undefined
}
detailsBind = [Link](user);
detailsBind() //'test'
2. let user = {
firstName : 'Test',
say(phrase){
alert(`${phrase}, ${[Link]}`)
}
}
let sayBind = [Link](user)
sayBind('Bye')
We are bingding the user method to the object, Now the this will always point to
thje object.
3. Using Bind to Preset the values:
function mul(a,b){
return a*b
}
const double = [Link](null,2);
const triple = [Link](null,3);
alert(double(3));
alert(triple(3));
4. Using currying to preset the values
function mul(a,b){
return a*b
}
function curry(f){
return function(a){
return function(b){
return f(a,b)
}
}
}
const mulCurry = curry(mul);
const multiplyByTwo = mulCurry(2);
const multiplyByThree = mulCurry(3);
alert(multiplyByTwo(10));
alert(multiplyByThree(10));
5. function f() {
alert([Link]);
}
f = [Link]( {name: "John"} ).bind( {name: "Pete"} ); //John because a function
cannot be rebound
f();
//Study ABOUT GitHub Actions and CircleCI
======Arrow functions===========
1. const data = {
title : 'Technology Stacks',
data : ['react js', 'html', 'css' , 'javascript'],
details(){
[Link](item=> {
alert(`${[Link]} : ${item}`)
})
}
}
[Link]() //Here the this inside forEach callback function will refer to
the this of the details method as we are using arrow functions.
=====Object Properties Configuration=========
Object properties besides value has three special attributes:
1. writable : If true the value cvan be chnaged, else its read-only.
2. enumarable : If true , it is listed in loops else noyt listed
3. configurable : If true , the property can be deleted and modified, else not.
By default in an object all the above are true;
const obj = {name : 'John'}
let descriptor = [Link](obj, 'name')
//{value: 'John', writable: true , enumarable: true , configurable : true}
//To chnage the above propertiesd we need to use [Link]()
[Link](obj,'name', {writable:false})
//Non-enumarable : To not include a Property in the loop
let obj ={
name: 'Test',
toString() {
return [Link];
}
}
for (let key in obj){
alert(key); //name, toString
}
[Link](obj,'toString',{enumartable: false})
for (let key in obj){
alert(key); //name
}
//Configurable:false prevents chnage in the property flgas and its deletion, while
allowing chnage in its value.
let user = {
name: "John"
};
[Link](user, "name", {
configurable: false
});
[Link] = "Pete"; // works fine
delete [Link]; // Error
//[Link] : It prevents addition or deletion of any properties of an object.
Here configurable is set to false. We can however modify the existing properties.
//[Link] : It prevents addition/deletion/modification of any properties.
Here configurable and writable are set to false.
//[Link]() : Return true if object has configurable as false
//[Link]() : return true if object has configurable and writable as
false.
====Prototypal Inheritance=======
It is a way in javascript to inherit properties and methods from other objects.
In Javascript objects have a hidden property [[Prototype]], that is either null or
refrence to another object.
That object is called a prototype. This prototype object contains methods which
can be utilized by other objects.
Example:
let child = {name : 'child'}
let parent = {name:'Parent' , address: 'Address'}
child.__proto__ = parent //This will set parent to be the prototype of childf.
[Link] = "Address"
Example:
const parent = {
name: "Parent",
address: "3110 stree1 ",
details(){
return 'Family details'
}
}
const child = {
name: "Child",
__proto__: parent
}
//The value of __proto__ can either be an object or null.
*** __proto__ is not the same as the property [[Prototype]]. It is the
getter/setter for [[Prototype]]
//The for in loop iterates over the interited properties too. To avoid this we need
to use the [Link](key)
let parent = {
name: 'parent',
address: 'address'
}
let child= {
name: 'child',
__proto__: parent
}
for(let key in child){
alert(key) //name, address
}
//We can make use of [Link]() to find the prototype chain.
[Link]([1,2,3])
//In order to add a custom method to the prototype we use [Link] =
function(){
alert(this)
}
=========CLASSES============
1. Class in Javascript is kind of a FUNCTION . If we do typeof Class it will be a
function.
Here JS creates a function named User and attaches any property inside of it to
[Link].
class User {
constructor(name){
this._name = name; //In order to make a variable protected to the class
there is a naming convention in which we add a underscore before the name. This
helps in encaptulation.
}
sayHi(){
alert(this._name)
}
}
const user1 = new User('Rajat');
[Link]() --- typeof User = function
2. Difference between Class and Constructor Function
1. A function created by class is labelled by a special internal property
[[IsClassConstructor]]:
2. Class methods are ennumerable. A class definition sets ennumerable flag to
false of all the definitions.
3. To add a property to a class we have Class Fields.
class User {
name="John"
getData(){ alert([Link]) }
4. class Button {
constructor(value) {
[Link] = value;
}
click() {
alert([Link]);
}
}
let button = new Button("hello");
setTimeout([Link], 1000); // undefined. Here since we are directly passing
the [Link] method as a function it loses its context and the this now points
to global object window.
5. In a child class if we have a method which overrides the method of the parent
class. And if we want to call the method of the parent instead of child we use
[Link]()
6. STATIC METHODS ND PROPERTY:
Static method are used to implement functions which belong to the class as a whole,
but not to any particular object.
Static methods are callable on classes but not on indiviual objects.
[Link]() will work but [Link]() wont work.
Similar to static methods we also have static properties.
Static methods are properties can be inherited.
7. PRIVATE AND PROTECTED PROPERTIES AND METHODS
In JS there are two types of properties and methods:
1. Public - accessible from anywhere.
2. Private - accessible only from inside the class. To make a property or method as
private we use #name.
private fields cannot be inherited.
3. There is also a Protected type which is accessible from inside the class and the
inherited class.
Protected properties are usually prefixed with an _underscore. This is not a rule
but a naming convention between developers.
4. To make a property as read-only we need to make a getter for the property but no
setter.
5. instanceof : The instanceof operator allows us to check whether an object belong
to a paricular class. eg. obj1 instanceof Object.
let arr = [1, 2, 3];
alert( arr instanceof Array ); // true
alert( arr instanceof Object ); // true
9. MIXINS
In JS we can only inherit from a single object and the class may extend only one
other class.
A mixin is a class containing methods that can be used by other classes without
without a need to inherit from it.
===========Error Handling============
1. try-catch only works for runtime errors and not syntax error.
The JS Engine first reads the code and then runs it. The error that occurs during
the reading of the code is called parse error. (syntax error).
2. try-catch works synchronoulsy. It wont work for below setTimeout as the
setTimeout itself is executed later.
try{
setTimeout(function(){
nondeclaredVar
})
}
catch(err){
alert([Link])
}
To make it work we needo add the setTimeout inside the try-catch.
3. catch(err) - err is an error obejct which JS generates containing information
about the error.
The main properties of the error object are
[Link] = "refrence Error", "Syntax Error", etc. ,
[Link].
[Link] A string with information about the sequence of nested calls that led to
the error.
4. Using throw keyword
let json = '{"name":"test"}'
try{
let data = [Link](json);
alert([Link])
}
catch(err){
alert([Link])
}
//This is print undefined and not enter the catch block. here we can use the throw
property to throw an user defined error.
let json = '{"name":"test"}'
try{
let data = [Link](json);
if(![Link]){
throw new Error('Age not present')
}
alert([Link])
}
catch(err){
alert([Link])
}
5. When a runtime error or a user defined Error(throw new Error) is encountered in
the try block the execution will shift to catch and no more code in the try block
will be executed.
6. The finally block will run everytime. It is used to execute a piece of code
which should run in both the scenarios , be it try or catch.
7. OUTPUT BASED:
function test(){
try{
return 1;
} catch(err){
alertt([Link])
} finally {
alert('finally')
}
}
alert(test()) //First finally will be printed and then 1 will be printed
function func() {
try {
return 1;
} catch (err) {
/* ... */
} finally {
alert( 'finally' );
}
}
alert( func() );
8. throw new Errorr(1) or throw new Error(true) is also an valid error.
==========================PROMISES and CALLBACKS==============
[Link] function: In JS, a callback function is a function which is passed as an
argument to another function and is executed at a later time. Typically it is
called once an asynchronous operation completes.
2. Callback hell/Pyramid of Doom
Callback hell is a situation when we have multiple nested callbacks. It happens
when we have multiple asynchronous operations and each operation relies on the
completion of the previous one.
3. Promise:
A Promise is an placeholder object in javascript which will hold information about
the eventual completion or failure of an asynchronous operation.
A promise object returned by new Properties have below internal properties:
1. state : Initially it is 'Pending' and then changes to either 'Fullfilled' when
resolve is called or 'Rejected' when reject is called.
2, result: Initially undefined but changes to value when resolve(value) is called
or error when reject(error) is called.
Example:
const promise = new Promise(function(resolve,reject){
setTimeout(()=> {
resolve('Promise is resolved!!!')
},5000)
})
Here before 5sec the promise will be:
Promise {<pending>}:
[[PromiseState]]: "pending"
[[PromiseResult]]: undefined
After 5 sec:
Promise {<fulfilled>: 'Promise is resolved!!!'}
[[PromiseState]]: "fulfilled"
[[PromiseResult]:"Promise is resolved!!!"
The executor should perform a job (usually something that takes time) and then call
resolve or reject to change the state of the corresponding promise object.
4. The executer function will call only one resolve or one reject. The others will
be ignored.
let promise = new Promise(function(resolve, reject) {
resolve("done");
reject(new Error("…")); // ignored
setTimeout(() => resolve("…")); // ignored
});
5. The function passed to Promise is called the executer function.
It has two callback function passed as arguments to it.
After the executer function gives a successfully result then the callback function
resolve is called.
After the executer function gives an error then the callback function reject is
called.
Example:
const promise = new Promise(function(resolve,reject){
setTimeout(()=> {
resolve('Promise is resolved!!!')
},5000)
})
[Link](res=> alert(res)).finally('End') //here End is printed first
[Link](res=> alert(res)).finally(()=> alert('end')) //here 'end' is printed
after the res.
6. To consume the Promise object we use the .then and .catch .finally methods.
[Link](
function(result) { /* handle a successful result */ },
function(error) { /* handle an error */ }
);
The first argument of .then is a function that runs when the promise is resolved
and receives the result.
The second argument of .then is a function that runs when the promise is rejected
and receives the error.
For only checking error we have catch(err=> ......) which is alernative for
[Link](null, function(err) ....)
.finally : It is used to perform cleanup activities.
finally does not have any information about the promise result.
1. Important points for the finally handler:
1. The finally handler does not have its own arguments
2. The finally handler does not return anything.. Even if it does it is
ignored. There is axception, if there is an error it goes to the next handler.
A finally handler doesn’t get the outcome of the previous handler (it has no
arguments). This outcome is passed through instead, to the next suitable handler.
If a finally handler returns something, it’s ignored.
When finally throws an error, then the execution goes to the nearest error handler.
7. In Promise chaining each .then returns a new promise, so that we can call the
next .then on it. The return statement of the .then method becomes the promise
result for the next .then method.
Example:
new Promise((resolve,reject)=> {
throw new Error("Error Revecived!!!!!")
}).catch(err=> {
alert(err)
}).then(res=> {
alert(res)
}) //Error Received undefined
Example:
// the execution: catch -> catch
new Promise((resolve, reject) => {
throw new Error("Whoops!");
}).catch(function(error) { // (*)
if (error instanceof URIError) {
// handle it
} else {
alert("Can't handle such error");
throw error; // throwing this or another error jumps to the next catch
}
}).then(function() {
/* doesn't run here */
}).catch(error => { // (**)
alert(`The unknown error has occurred: ${error}`);
// don't return anything => execution goes the normal way
});
*** When the error is handled successfully in the .catch block then the next .catch
will also execute.
new Promise((resolve,reject)=> {
throw new Error("Error Revecived!!!!!")
}).catch(err=> {
alert(err)
}).then(res=> {
alert("Next then call!!")
})
PROMISE APIs
1. [Link] -> [Link] takes an iterable and returns a new promise.
The new promise resolves when all the listed promises are resolved or one of the
promises is rejected.
In [Link]() when one of the promises reject , it result in ignoring the other
promisess. these other promises are not cancelled but ignored. There is no concept
of cancelling a promise.
In [Link]() along with promises we can also pass primitive values like 1,2,3,
[Link](new Promise(resolve=> setTimeout(1),1000),1,2)
[Link]([
new Promise(resolve => setTimeout(() => resolve(1), 3000)), // 1
new Promise(resolve => setTimeout(() => resolve(2), 2000)), // 2
new Promise(resolve => setTimeout(() => resolve(3), 1000)) // 3
]).then([Link](alert)); //[1 2 3] we use [Link]() as s
alert() converts everything to string. without it output would be 1,2,3'
[Link]([
new Promise(resolve=> setTimeout(()=> resolve(1),3000)),
new Promise((resolve,reject) => setTimeout(()=> reject(2),2000)),
new Promise(resolve => setTimeout(()=> resolve(3),1000))
]).then(res=> alert(res)).catch(err=> alert(err)) //2
2. [Link]() -> It will wait for all the promises to settle and will
return an array with the status and value of the promises.
[Link]([
new Promise(resolve=> setTimeout(()=> resolve(1),3000)),
new Promise((resolve,reject) => setTimeout(()=> reject(2),2000)),
new Promise(resolve => setTimeout(()=> resolve(3),1000))
]).then(res=> alert([Link](res))).catch(err=> alert(err))
output: [{"status":"fulfilled","value":1},{"status":"rejected","reason":2},
{"status":"fulfilled","value":3}]
3. [Link]() waits for first settled promise an returns its result. It can be a
fulfilled promise or rejected promise.
4. [Link]() waits for the first fulfilled promise. If the result of all the
promises are erejected then it will return the array of rejected result
==========
Promification: It is the conversion of a function that accepts a callback into a
function that returns a promise.
======MICROTASKS==========
let promise = [Link]();
[Link](()=> alert("Async Promise Done"))
alert("synchronous code!!") //order of execution: "sync code!!" "async promise
done"
** Promise handlers .then, .catch and .finally are queued in the microtask queue.
They are executed only when the callstack is empty
let promise1 = [Link]();
let promise2 = [Link]();
promise1
.then(() => [Link](1))
.then(() => [Link](2));
promise2
.then(() => [Link](3))
.then(() => [Link](4))
=======ASYNC/AWAIT========
** The word async before a function means that the async function will always
return a promise.
1. The async function will always return a promise.
2. The await keyword works only inside promises.
The await keyword makes javascript wait until the promise is settled and
returns its results.
The await keyword suspends the function execution until the promise settles and
then resumes it with the promise result. In the meantime JS can execute
otherscripts andf event handlers.
** Async/Await is a mopre elegant syntax of getting the promise result than
[Link] and its more easier to read and write.
=====================================================================MODULES=======
===========================================
1. For the script to be treated as a module we must use <script type="module>
2. Modules always work in strict mode.
3. A module code is evaluated only the first time when imported. When there are
other imports ofthe same module it uses the same thing.
4. Inside a module this is undefined.
<script type="module>
alert(this) //Inside a module this is undefined.
</script>
5. Import/Export statements does not wo9rk inside conditional statements.
if (something) {
import {sayHi} from "./[Link]"; // Error: import must be at top level
}
For this we require dynamic imports and exports.
6. Tree shaking is a concept in javascript which removes unused exports.