Javascript Tips

Advance JavaScript Runtime Reference :

Namaste 🙏 JavaScript
Lydia Hallie

Object Clone Secrets

1. Here “z” property will not display

//Object clone secrets
//copy/deep clone an Object
//1. JSON.parse, JSON.stringify
//2. Object.assign

let obj = {x: 1, y:2, z: function(){}}
let obj1 = JSON.parse(JSON.stringify(obj))
obj1.x = 10;

console.log(obj)
console.log(obj1)

2. “NaN” will create “NULL” value

let obj = {x: 1, y:2, z: NaN }
let obj1 = JSON.parse(JSON.stringify(obj))
obj1.x = 10;

console.log(obj)
console.log(obj1)

Parse,Stringify are slow perform, time taking process. The another way we can use is “Object.assign”
II. Object.assign is better approach, but it has some drawbacks

let obj = {x: 1, y:2 , t: NaN}
let obj1 = Object.assign({}, obj, {w:1})
obj1.x = 10;

console.log(obj)
console.log(obj1)

b. Both will have the same innerObj value, bcz obj will have the reference of the inneer object

let obj = {
  x: 1,
  y: 2,
  t: {innerObj: 1}
};
let obj1 = Object.assign({}, obj, { w: 1 });
obj1.z.innerObj = 10;

console.log(obj);
console.log(obj1);

Solution : use underscore library => _.deepClone method

Higher Order Function / First Class Function

1. We can pass function as argument

function myfun(arg){
	arg()
}

2. A function can return another function

function myfun() {
	return function(){....}
}

3.we can store a function into a variable

var myfunction = function () {
.....
}

4. we can store a function into an object

var obj = {
	myfun: function () {...}
}

5. we can store a function into an array

var arr = [function() {....}, function() {....}]

Higher Order function example : 
arr.map(function(item, i) {
	console.log(item)
})

Remove duplicate elements from Array

Method 1

let arr = [1,2,3,4,555,4,2,1]
function removeDuplicate(arr) {
	let result = [];
	for(let i = 0; i< arr.length; i++){
		if(result.length === 0){
			result.push(arr[i])
		}
		if(result.indexOf(arr[i] === -1)){
			result.push(arr[i])
		}
	}
	return result;
}
console.log(removeDuplicate(arr))

Method 2 : Using Object

let obj = {
"name":"984",
"yourname": "9835",
"yourname":"2587"
}
console.log(obj)
//"yourname" will display once, key can not be repeated

function removeDuplicate(arr) {
	let result = {};
	for(let i = 0; i< arr.length; i++){
		result[arr[i]] = 1
		//key			//Value 		
	}	
	return Object.keys(result); // ["1", "2"...]
	
	//To avoid string array, will use map
	return Object.keys(result).map(val => +val);
}

Method 3 : Using Set operator, it will remove duplicate values

function removeDuplicate(arr) {	
	console.log(...new Set(arr)) // 12345
	return[...new Set(arr)] // Group to array-> [1,2,3,4,5]
}

Callback & Promise

function cbExample (num, cb){
	var i;
	for(i=0; i< = num; i++){
		console.log(i)
	}
	cb(i)
}

cbExample(10, (lastnumber)=>{
	console.log('This is last number ' + lastnumber)
})

2. callback Hell

cbExample(10, (lastnumber)=>{
	console.log('This is last number ' + lastnumber)
	cbExample(20,()=>{
		cbExample(20,()=>{
			cbExample(20,()=>{
		
			})
		})
	})
})

Callback & promises part - 2

To avoid callback hell, we use promisse

Syntax :

let promise = new Promise((res, rej)=>{
	res();
	rej();
})

promise.then().catch()

Example :

let promise = new Promise((res, rej)=>{
	res(1);
	//rej("Some random error");
})

promise
	.then((data)=> {
		console.log('Then ' + data)
	})
	.catch(()=>{
		(err)=> {
		console.log('Error ' + err)	
	})

Inside the Promise, we will make API call, if it is success we pass data to resolve else pass to reject

let promise = new Promise((res, rej)=>{
if(success) {
	res(1);
} else {
	rej("Some random error");
}
})

We can use it for alternate to Callback hell

Callback & Promises - 2

let promise = new Promise((res, rej)=>{
    if(success) {
        res(2)
    } else {
        rej("Some Random Error")
    }
})

promise.then((data)=>{  console.log('Then ' + data) ; return data+1;})
promise.then((data)=>{  throw new Error('Some Error'); console.log('Then ' + data); return 0 })
promise.then((err)=>{  console.log('Error ' + err) })

Promise All - Wait until all get executed

let promise1 = new Promise((res, rej)=>{
    setTimeout(()=> res(1), 1000);
})
let promise2 = new Promise((res, rej)=>{
    setTimeout(()=> res(2), 1000);
    //setTimeout(()=> res("error"), 2000);
})
let promise3 = new Promise((res, rej)=>{
    setTimeout(()=> res(3), 2500);
})

if any error , it will not come to then part

Promise.all([promise1,promise2, promise3])
        .then(console.log)
        .catch(console.log) //[1,2,3]

Any one promise completed, those value will be returned

Promise.race([promise1,promise2, promise3])
        .then(console.log)
        .catch(console.log) //1

Convert async's Promise to sync is async/await
Promise Sample :

let promise = new Promise((res, rej)=> {
    setTimeout(()=> res(0), 1000);
})

console.log('a');
promise.then((data)=>{console.log('Then : ' + data); return data+1;})
        .catch((err)=>{console.log('Error ', + err)})

console.log('b')

async/await Sample :

async function someFun() {
    console.log('a');
    let data = await promise;
    console.log('Inside async : '+ data)
    console.log('b')
}

someFun(); //'a' Inside async : 0, 'b'
//Self Eexecution function 
(async function(){
    console.log('a');
    let data = await promise;
    console.log('Inside async : '+ data)
    console.log('b')
})()

setInterval, setTimeOut

<body>
    <div id="txt"></div>
</body>

let textNode = document.getElementById('txt');
let i = 1;
let interval = setInterval(()=>{
    textNode.innerText = 1;
    i++;
}, 1000)
setTimeout(function(){
    clearInterval(interval);
    textNode.innerText = 'Welcome to UI Gems'
}, 6000)

Function Currying


// add(1)(2) => 3 ?? How to write this function

function add(a) {
    return function(b) {
        return a + b;
    }
}

console.log(add(1)(2))

2. Example : Another way to do same

function add(a) {
    return function () {
        return a + b;
    }
}

let add1= add(1);
console.log(add1(2))

Difference between function and arrow function

1 ) Arrow function is anonymous function not named function
ex:

function myfunction(arg) { return arg; } // correct :)
(function(arg) { return arg; })(1); // correct :)
const myfunction = (arg) => { return arg; } // correct :)
myfunction(arg) =>{ return arg; } // wrong :(

2) Lexical 'this' & 'arguments' are not available inside arrow
function, if 'this' variable is used then it will point to outer scope

3) Arrow function cannot be called/constructed with 'new' keyword
ex:

function User() {}
new User() // correct :)

const User = () => {}
new User() // wrong :(

Note:
Normal functions are both contructable and callable
Arrow functions are only callable
Class constructors are only constructable

function test() {
  this.a = 10;
  let that = this;
  setTimeout(function() {
    console.log('inside setTimeout ' + that.a);
  }, 10);
  console.log('outside setTimeout ' + this.a);
}
let x = new test();
//Output
//nside setTimeout 10
//outside setTimeout 10

Using Bind() function, bind the outer function into the inner function, heret 'this' will point to outer function

function test2() {
    this.a = 10;
    setTimeout(function() {
      console.log('inside setTimeout ' + this.a);
    }.bind(this), 10);
    console.log('outside setTimeout ' + this.a);
  }
  let x = new test2();

//nside setTimeout 10
//outside setTimeout 10

Using arrow function, arrow function will not have 'this' keyword, so it give same output

function test3() {
    this.a = 10;
    setTimeout(() => {
      console.log('inside setTimeout ' + this.a);
    }, 10);
    console.log('outside setTimeout ' + this.a);
  }
  let x = new test3();

//nside setTimeout 10
//outside setTimeout 10

ARGUMENTS

function funcWithArg() {
    console.log(arguments)
} //[1,2,3]

const funcWithArg1 = () =>{
    console.log(arguments)
} //Error

To use the arguments with arrow function , we can choose '...' spread operator

const funcWithArg1 = (...args) =>{
    console.log(args)
} // [1,2,3]

funcWithArg(1,2,3)
funcWithArg1(1,2,3)

Spread Operator

let arr1 = [1,2,3]
let arr2 = [arr1,4,5,6]
let arr3 = [4,5,6]
console.log(arr2) //[[1,2,3],4,5,6]
console.log(arr1.concat(arr3)) //[1,2,3,4,5,6]

let arr4 = [...arr1,4,5,6]
console.log(arr4)
console.log(Math.max(...arr4))

1. let ar1 = [1,2,3]
let ar2 = ar1;

ar2.push(4)
console.log(ar1) //[1,2,3,4], 
//we use speard to create array without reference , and use math FunctionStringCallback

it will insert into the first array, bcz of reference

To avoid it , we can use spread operator

let ar1 = [1,2,3]
let ar2 = [...ar1]
ar2.push(4)

console.log(ar1) 
console.log(ar2)

Shallow Copy

let obj1 = {a:1};
let obj2 = {b:1}

let ar1 = [obj1, obj2];
let ar2 = [...ar1]

ar2.push(10)

console.log(ar1) 
console.log(ar2) 
//[{a:1}, {b:2}, 10]

UIGems -Playlist

How to use the fetch() method to make multiple API calls with vanilla JavaScript

Waiting for multiple all API responses to complete with the vanilla JS Promise.all() method

Leave a Reply

Your email address will not be published. Required fields are marked *