Javascript developed by Brendan Eich, Netscape,1995. Mocha->Livescript->javascript
Developed By: Brendan Eich at Netscape in 1995. Name Evolution: Mocha → LiveScript → JavaScript. Script Tag:
<script type="text/javascript">
type=”text/javascript” is not needed’use strict’;
to use only latest functionality of javascript versionsbreak,as,any,switch,case,if,throw,else,var,number,string,get,module,type,instanceof,typeof,finally,for,enum,export,while,void,this,new,null,super,catch,let,static,return,true,false
named storage of a data, case sensitive
Note:
specifies type of data in a variable
Data Type | Range | typeof Return |
---|---|---|
Number | ±9,007,199,254,740,991 | "number" |
BigInt | No limit | "bigint" |
String | sequence of characters | "string" |
Boolean | true or false |
"boolean" |
Undefined | undefined | "undefined" |
Null | null | "object" |
Symbol | N/A | "symbol" |
Object | key-value pairs | "object" |
Function | N/A | "function" |
Note: number also support nfinity, -Infinity and NaN
let arr = new Array();
let arr = [];var arr[“name”,’age’,’job’]=[“rajesh”,”12”,’vetti’]; console.log(arr[“name”]); //rajesh
[1,2,3].includes(2); //return true false
[1,2,3].findIndex (2); //return true false
“Hello world”.include(“world”); //return true false
“Hello world”.startswith(“H”, index); //return true false
“Hello world”.endswith(“d”, index); //return true false
“sorry “.repeat(100); //print sorry 100 times
String.raw”it is not new line /n” //print as it is - it is not new line /n
let billion = 2000; //can written as let billion = 2e3;
let millisec = 0.002; //can written as let millisec = 2e-3
Hexad: alert( 0xff ); // 255 alert( 0xFF ); // 255 (the same, case doesn’t matter)
num.toString(base); eg.a=3; a.toString(2); //0011 default base is 10
Two dots: directly called from number. 3.toString(2); //0011
Infinity (and -infinty) represents great (or less) than anything. isFinite(number); //checks whether its not infinity
NaN represents a non number type isNan(number); //checks whether is not number
Destructing assignmet: var [a,b]=[1,2];
var sample=[a,b]; sample=[1,2]; a=1,b=2
if
if..else
nested if else if
switch case
for
while
do…while
Loop control:
break:
continue:
for…in for(key in obj){ console.log(obj[key]);}
for…of for(arrKey of arr){ console.log(arrVal);}
function functionName(){…body….}
functionName(); //function calling
closure can remember environment variables in which it was created, allowing it to access variables from that scope even after the outer function has finished executing.
function outerFunction() {
let outerVariable = "I'm from outer scope!";
function innerFunction() {
console.log(outerVariable); // Accessing outerVariable from outerFunction
}
return innerFunction; // Returning the inner function
}
const closureFunc = outerFunction(); // outerFunction executes, but innerFunction is still accessible
closureFunc(); // Logs: I'm from outer scope!
let functionName = (parameter)=>{…function body..…}; it does not have its own this object. eg:
var obj = {name:"rajesh",
getName: function(){ (function(){console.log(this.name)})(); },
getNameArrow: function(){ (()=>{console.log(this.name)})(); }
}
obj.getNameArrow(); //print rajesh
obj.getName(); //undefined
function bigNum(a,b, ...argArray){
//a=1,b=2,arrgArray is an array[3,4,5]
}
We can combine two arrays. a=[1,2,3]; b=[4,5]; c= […a,…b]; //c is [1,2,3,4,5]
console.log(…a); //1 2 3
We can combine two arrays. A=[3,4,5];b=[1,2]; a.push(…b); instead of // Array.prototype.push.apply(a,b);
Note: this operator also use for shallow copy(only first level not applicable for nested objects)
var a={name:'UST', age:17};
var b= {...a}; //shallow/new copy
b.age = 18; console.log(a.age);//17
let user = new Object();
let user = {};
Comparing object : 1. individual values, 2. json stringify
Const object: it is changeable, but cannot be reassign
Clone object: newObj = Object.assign({},oldObj);
Garbage collections: The variable and objects which cannot be reached, get destroyed
Primitive datatypes is no an object, but a object wrapper is temporarily created while using it functions eg.str.split() . But for null,undefined there is no functions and no object wrapper created. eg. str = new String("rajeh"); str.test=5; console.log(str.test);//undefined
Es6
function Cricketer(name,age,position){
this.name=name; this.age=age; this.position=position;
}
Cricketer.prototype.changePosition=function(position){
this.position=position;
}
var cricketer = new Cricketer("rajesh","22","batting");
console.log(cricketer);
crickter.changePosition("bowler");
console.log(crickter);
class Cricketer {
constructor(name,age,position){
this.name=name;this.age=age;this.postion=position;
}
changePosition(position){
this.position=position;
}
}
let crickter = new Crickter("rajesh","2","batting");
console.log(crickter);
crickter.changePosition("bowler");
console.log(cricketer);
These methods are useful for controlling the value of this within a function
var obj = {num:2};
var func=function(a,b){ console.log(this.num+a+b);}
func.call(obj,1,2);
//call allows you to explicitly set the context (the value of this)
func.apply(obj,[1,2]);
//apply same like call but get arguments as array
var bound = func.bind(obj);
bound(1,2); //bind unlike call,apply it won’t immediately invoke, instead return a function
Note: Arrow functions (=>) in JavaScript do not have their own this binding and do not have call, apply, or bind methods.
var Car = function(){ this.color='red'; }
Car.prototype.getColor=function(){ return this.color; }
var ToyCar = function(){ };
ToyCar.prototype=Object.create(Car.prototype);
ToyCar.prototype.color='orange';
var obj = new ToyCar();
console.log(obj.getColor());
It is real alternative for
let sayHiMixin = { proto: anotherObject} //but we should nor use proto so we using Object.create
var obj1 = {drive:function(){return ‘i can drive’;}, walk:function(){return ‘i can walk’;}};
var obj2 = { drive(){return super.drive();}}
Object.setPrototypeOf(obj2.obj1); //obj1 will get obj1 as a prototype
obj2.walk(); //call walk function in obj1
obj1.drive(); //call drive function in obj, because of super object.
var obj1 = {color:’red’};
var obj2={}; Object.assign(obj2,obj1); //1st way to assign
var obj3 = Object.assign({}.obj1); //another way to assign
var obj4 = function(){a,b}{ Object.assign(this,{a,b});} //also used in constructor
collection of unique values
var mySet = new Set();
mySet.add(1).add(2).delete(1).clear();;
var mySet = new Set([1,2,3,5,4,4,4,4,4]); //mySet is 1,2,3,4
console.log(mySet.size);
for(val of mySet) { console.log(val);} //can be iterable
can convert Sets to array: console.log([..new Set([1,2,2,3])]);
Array.from(new Set([12,2,3]));
can have only as objects
var myWeakSet = new WeakSet([{a:1},{b:2}]);
myWeakSet.add(1); //throw error
myWeakSet.add({a:1});
can have more than one object key
var myMap = new Map();
myMap.set(a,’a’).set(b:’b’).set(a:’c’).delete(b);
for(let [key,value] of myMap.entries()){
console.log(key,value);
}
new Map();
map.set(key,value)
map.get(key)
map.has(key)
map.delete(key)
map.clear()
map.size
Super constructor
class Car{
construct(arg){}
func1(){}
static func2(){} //inside static we cannot use this object variables }
class Honda extends Car{
constructor(arg){ super(arg);….} //must call super constructer, otherwise error will occur
func1(); }
var obj = new Car(arg);
object represents result of asynchronous operation, allowing you to handle success or failure once the operation is complete.
var promise = new Promise(function(resolve,reject){
setTimeout(function(){
success=true;
if(success){resolve(‘result’);} //wait until resolve function beeing called
else{reject(‘sorry’);} },1000);
});
promise.then( function(resolveResult){ ….handle resolveResult…}).catch(function(rejectResult){….handle reject…});
promise.then( function(resolveResult){ ….handle resolveResult…},function(rejectResult){….handle reject…});
promise.then( null,function(rejectResult){….handle reject…}); //to handle only error
promise.all([promise1, promise2….promisen]);
var promise1 = new Promise((resolve,reject)=>{setTimeout(resolve("rajesh"),3000);});
var promise2 = new Promise((resolve,reject)=>{setTimeout(resolve("23"),3000);});
var promise3 = new Promise((resolve,reject)=>{setTimeout(resolve("not a bad guy"),3000);});
var callSync=async ()=>{
var promresult1 = await promise1; console.log("his name is :"+promresult1); //his name is rajesh
var promresult2 = await promise2; console.log("his is :"+promresult2); //his is 23
var promresult3 = await promise3; console.log("sometimes he is :"+promresult3); //his not a bad guy
return 'success';
}
callSync().then((resultText)=>console.log('result is '+resultText));
Await should use only inside async: syntax: await promiseName; //the js will pause until result come from promise
var arr=[1,2];
var iterator=arrSymbol.iterator;
console.log(iterator.next()); //{value:1,done:false}
console.log(iterator.next()); //{value:2,done:false}
console.log(iterator.next()); //{value:undefined,done:true}
function generatorFunc(){ yield 1; yield 2; yield anotherGenerator(); yield 5;}
function* anotherGenerator(){yield 3; yield 4;} //each yield is not created until it gets called by next()
var generator = generatorFunc();
console.log(generator.next()); //{value:1,done:false}
console.log(generator.next()); //{value:2,done:false}
console.log(generator.next()); //{value:3,done:false}
console.log(generator.next()); //{value:undefined,done:true}
Unexpected token
a is not defined
a is not a function
event listeners fires not only on single element, but also fires from all its Dom parents
event listeners fires not only on single element, but also fires from all its Dom decendents
manage error gracefully
try {
let result = someFunction();
} catch (error) {
console.log("An error occurred: " + error.message + error.stack + error.name);
} finally {
console.log("This will always run, even if an error occurs.");
}
Throw statement: throw new Error("Age cannot be negative");
Customer error: throw new TypeError("This is a type error");