JavaScript Notes — 3
Functions on Promises, IIFEs, setTimeout, setInterval, Pass by Value vs Pass by Reference
Example of a function taking function in input:
function b (y) {
console.log(y);
}
function a (x) {
x('abc');
}
a(b);
// Output: abcWe can define the other function at the time of calling of first function also.
function func1 (func2) {
func2('abc');
}
func1( function f (x) {
console.log(x);
}
);
// Output: abcWe can understand it like this that a variable which takes the definition of a function can act as a function.
For example: In the below code variable done takes the definition of a function and behaves like that function.
function fD (done) {
let abc = "This is a sentence" ;
done(abc) ;
}
fD ( function (data) {
console.log(data) ;
} ) ;
// Output: This is a sentencePromises
Promises are a way to handle asynchronous communication. Example of a function returning a Promise
function fD(correct){
return new Promise ( function (resolve, reject) ) {
let stuff = "some value" ;
// Incomplete code. Code is just for understanding purposes. - - -
if(condn_1){
resolve (stuff) ; // .then() will run. We are passing `stuff` also.
} else {
reject ( new Error ("Operation failed") ) ; // .catch() will run.
}
}) ;
}
// fD() denotes function fD has been called and it will return a Promise object,
// upon the returned promise we can apply .then and .catch
fD()
.then(function(data){
console.log(data)
})
.catch(function (err) {
console.log(err)
}) ;
// We could have dealt with .then() or .catch() later on alsoWhile creating a Promise in the above example, we could have also used Arrow function, which is a more popular way.
// What we did earlier
return new Promise ( function (resolve, reject) ) { .. }
// What we can also do
return new Promise ( (resolve, reject) => { .. } );Note: If promises are linked, .catch() can catch error in any of the linked promises.
Functions which can be applied over Promise
Promise.all( [ ] )Takes array of promises.
Immediately rejects, if any one rejects.
Resolves when all are resolved.
Example:
Promise.all( [p1, p2, p3] )
.then( [resp1, resp2, resp3] )
.catch((err)=>{}); // As we noted, only one catch is sufficient for multiple chained Promises Promise.allSettled( [ ] )Takes array of promises.
Always resolves and returns an array of status of indivial promises.
Waits until each promise is settled (either resolved or rejected).
Example:
Promise.allSettled( [p1, p2, p3] )
.then( results => console.log(results) );
/*
Output can be like this:
[
{ status: 'fulfilled', value: 'ResponseX' },
{ status: 'rejected', value: 'Error in second request' },
{ status: 'fulfilled', value: 'ResponseY' }
]
*/Promise.race( [ ] )Takes array of promises.
Resolves or rejects as soon as any one promise gets resolved or rej.
Example:
const p1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Promise 1 resolved');
}, 1000);
});
const p2 = new Promise((resolve, reject) => {
setTimeout(() => {
reject('Promise 2 rejected');
}, 500);
});
const p3 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Promise 3 resolved');
}, 1500);
});
Promise.race([p1, p2, p3])
.then((result) => {
console.log('Race resolved with:', result);
})
.catch((error) => {
console.log('Race rejected with:', error);
});
/*
Output:
Race rejected with: Promise 2 rejected
Explanation:
P2 is fastest. Which is getting rejected. And thus .race gets rejected.
*/Another example. p3 is fastest which is getting resolved and thus .race gets resolved.
const p1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Promise 1 resolved');
}, 1000);
});
const p2 = new Promise((resolve, reject) => {
setTimeout(() => {
reject('Promise 2 rejected');
}, 500);
});
const p3 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Promise 3 resolved');
}, 150);
});
Promise.race([p1, p2, p3])
.then((result) => {
console.log('Race resolved with:', result);
})
.catch((error) => {
console.log('Race rejected with:', error);
});
/*
Output:
Race resolved with: Promise 3 resolved
*/Promise.any( [ ] )Takes array of promises.
Resolves if any one promise is resolved. Rejects if all promises are rejected.
Immediately Inovked Function Expression (IIFE)
Syntax: (Define with or without name) (call);
Examples:
Get Sriram’s stories in your inbox
Join Medium for free to get updates from this writer.
IIFE taking no input:
(function(){
console.log('green');
})();
// outputs greenIIFE taking simple input:
(function(a, b){
console.log(a+b);
})(5, 6);
// outputs 11 IIFE taking function as input (And we know that while passing function as argument, we only give name):
function y (a, b){
console.log(a+b);
}
(function(x){
x(5, 10);
})(y);
// outputs 15IIFE taking multiple functions as input:
(function(a, b){
a("3^4 is", b(3, 4));
})(console.log, Math.pow);
// outputs 81 Nested IIFEs
The following code works:
(function f1(x){
console.log(x);
})(
(function f2(){
return 5;
})()
);
// outputs 5Note: The above code works. But now understand that why the below code doesn’t work:
(function f1(x){
console.log(x);
})( // < - - Line B
(function f2(){
return 5;
})(); // < - - Line A
); In this code, we have added a semicolon after IIFE f2 has been called. But f2 gets executed before the semicolon itself and the semicolon is treated independently which terminates the opening bracket at Line B prematurely leading to error. So, in cases of nesting of any entities be it IIFEs or Promises, it is advicable to not use semicolons.
setTimeout, setInterval
setTimeout:
Runs once after a given time interval.
It takes two parameters:
1. function to run
2. time after which the function has to run (in milliseconds)
Syntax:
Using Anonymous functions:
let i = 5;
setTimeout( function(){
console.log(i);
}, 100);
// Outputs: 5 Or, using Arrow functions:
let i = 5;
setTimeout( ()=>{
console.log(i);
}, 100);
// Outputs: 5setTimeout(a, b); // run func `a` only once after b ms
setInterval(a, b); // run func `a` after every b msTo cancel setInterval after sometime, we can pass its reference to clearInterval in setTimeout or we can keep a counter variable.
Example:
function f1 (){
console.log("Hello");
}
let x = setInterval(f1, 1000); // run f1 after every 1s
setTimeout(f2, 3000); // run f2 once after 3s which will stop f1
function f2(){ // Due to hoisting, this will go up
clearInterval(x);
}
/*
Output:
Hello
Hello
*/Pass by Value vs Pass by Reference
JavaScript only supports Pass by value.
Que. When we pass an array to a function and make some changes to it, the changes get displayed even outside the function. Doesn’t it makes it pass by reference, like in C++?
Ans. No. In case of array, the changes made is also reflected outside, because in case of arrays, when we pass an array, we actually pass a pointer which points to the location where the array is stored.
So, the pointer is still passed by value, and the changes we make inside a function is performed on the reflected location, which persists everywhere.
Similar is the case with objects.
Note: If an array or an object is declared constant, we can still edit existing values, add new values (or even sort the array). A constant array or object just means that it defines a constant reference to an array / object. Because of this, we can still change the elements of a ‘constant’ array / object.
Strings are immutable in JavaScript.








