JS vars,loops, functions
Async vs sync
Callbacks
Callback explaination visualization "http://latentflip.com/loupe/"
// callbacks
function square(n){
return n*n;
}
function cube(n){
return n*n*n;
}
function sumOfSomething(a,b,fn){
const val1 = fn(a)
const val2 = fn(b)
return val1+val2
}
sumOfSomething(10,20,cube); // 500
sumOfSomething(10,20,square); // 9000
// reading a file it is callback function
const fs = require("fs");
fs.readFile("data.txt",'utf-8', (err, data) => {
console.log(data);
})
function sumOf100(n){
for(let i=0;i<n;i++){
console.log(i);
}
}
function calculation(){
let n=10
sumOf100(n);
}
setTimeout(calculation,1000);
console.log("Welcome to Hello!!!")
Promises
const fs = require("fs")
function readingFile(){
console.log("inside file function");
return new Promise(function(resolve){
console.log("inside promise")
fs.readFile("data.txt","utf-8", function(err, data){
console.log("Before resolve");
resolve(data)
})
})
}
function onDone(data){
console.log(data);
}
var a = readingFile().then(onDone)
Here we are returning promise. the resolve will through the data to then function it is calling the callback onDone() function with data as argument.It has the three states
Start
Pending
resolved
var d = new Date();
var d = new Promise(function(onDone){
setTimeout(function(){
resolve("foo");
}, 2000);
})
function callback(data){
console.log(data);
}
d.then(callback);
console.log(d); // output: Promise { <pending> }
Async- await
function sunkaraAsyncFunction(){
let p = new Promise(function(resolve){
// do some async logic here!!!
resolve("hi there!!") // the is value variable in callback
});
return p;
}
function main(){
sunkaraAsyncFunction().then(function(value){
console.log(value);
});
}
main()
// output: hi there!!
Now lets make the main as async function the .then syntax be removed using `async in function <name>
` while calling the promise use await store it in a variable. It is sytactic sugar. The promise should be in async block with await.
function sunkaraAsyncFunction(){
let p = new Promise(function(resolve){
// do some async logic here!!!
setTimeout(function(){
resolve("hi there!!") // the is value variable in callback
},1000)
});
return p;
}
async function main(){
let val = await sunkaraAsyncFunction()
console.log(val);
}
main()
// output: Promise { <pending> }
the resolve return the data and await will store that data.
map(), filter(), arrow() functions
Arrow functions:
/*
Arrow Functions
*/
function sum(a,b){
return a+b;
}
const sum = (a,b) =>{
return a+b;
}
app.get("/",(req,res){
})
app.get("/",(req,res)=>{
})
const ans = sum(1,2)
console.log(ans)
map: Given an array give me back an array each element multiplied by 2. map() works on top of arrays
// Ugly way to write this
const input = [1,2,3,4,5]
const newArray = []
for(let i=0;i<input.length;i++){
newArray.push(input[i]*2)
}
function multiply(ele){
return ele*2;
}
const arr = [1,2,3,4,5];
const newArr = arr.map(multiply)
/*
or
const newArr = arr.map(function(i){
return i*2
})
*/
console.log(newArr);
Here every value is being passed to multiply function. how this happens? the map() will take care!!.. Thanks to JS.
filter(): Give me all the even values in an array
// ugly way to write code!!!
const arr = [1,2,3,4,5];
const newArr = []
for(let i=0;i<arr.length;i++)
{
if(arr[i]%2==0){
newArr.push(arr[i])
}
}
console.log(newArr)
using filter() it is on top of arrays. the filter function is using the logic function either true or false then for each element checking the logic function return values then finally giving all the values satisfied logic
const arr = [1,2,3,4,5];
function filterLogic(n){
if(n%2==0){
return true;
}
else{
return false;
}
}
const ans = arr.filter(filterLogic);
/*
or
const ans = arr.filter(function(i){
if(n%2==0){
return true;
}
else{
return false;
}
})
*/
console.log(ans)
Write the function how map() is processing internally
/*
here fn is the logic function we havee to pass to the map
function
*/
const map = (arr,fn)=>{
const transformedArr = [];
for(let i=0;i<arr.length;i++){
transformedArr.push(fn(arr[i]))
}
return transformedArr;
}
reduce: It reduces all the elements of the array to a single value by repeatedly applying a function. It is an alternative of using a loop and updating the result for every scanned element. Reduce can be used in place of the following code:
function product(a, b){
return a * b;
}
arr = new Array(1, 2, 3, 6, 5, 4);
var product_of_arr = arr.reduce(product)
console.log(product_of_arr)