Promisification in JavaScript is a concept to convert the callback functions into a regular function, returning the promise.
The reason to convert the callback functions into promises is that when you need to write the nested callback functions, it increases the complexity of the code. So, you can write a function returning the promise.
In JavaScript, you can pass the function as an argument of another function called the callback function. The callback functions are used to handle the asynchronous task.
Let’s first write an example of the callback function.
Callback Function
Example
In the below code, we have passed the callback function as a last argument of the getSum() function. The getSum() function calls the callback function after passing the error and resultant sum value as an argument.
Open Compiler
<html><body><div id ="output">The sum of5 and 10 is:</div><script>functiongetSum(p, q, callback){let sum = p + q;setTimeout(()=>callback(null, sum),100);}getSum(5,10,(err, sum)=>{// callback function
Lets perform the promisification of the callback functions discussed in the above example.
Promisification of Callback Fucntion
Example
Lets understand the below code step by step.
Step 1 − First, we have created the findSum() function. It takes the p1, p2, and callback function as a parameter.
Step 2 − Next, the findSum() function checks whether the p1 and p2 are valid. If not, it calls the callback function by passing the error as an argument.
Step 3 − In other cases, it calls the callback function by passing the sum and message as arguments.
Step 4 − Next, we have defined the promisifyFunc() function, which takes the function as an argument that is needed to promisify.
Step 5 − The promisifyFunc() function returns the function, and that function returns the promise.
Step 6 − In the promise, we have defined the callbackFunc() function, which resolves or rejects the promise based on the argument it receives.
Step 7 − Next, we insert the callbackFunc() function into the args array and use the call() method to call the func function, which we received as a parameter of the promisifyFunc() function.
Step 8 − After that, we call the promisifyFunc() function and store the returned function in the getSUmPromise() function.
Step 9 − When you execute the getSumPromise() function, it returns the promise, which you can consume the then() and catch() method.
Open Compiler
<html><body><div id ="output"></div><script>let output = document.getElementById("output");constfindSum=(p1, p2, callback)=>{if(!p1 ||!p2){returncallback(newError("Missing dependencies"),null);}const sum = p1 + p2;const msg ='The sum of numbers is '+ sum;returncallback(null, sum, msg);// We call the callback function}functionpromisifyFunc(func){return(...args)=>{// Returning a functionreturnnewPromise((resolve, reject)=>{// Returning a promise// Defining a custom callback for the functionfunctioncallbackFunc(err, ...data){if(err){returnreject(err)}returnresolve(data)}
args.push(callbackFunc);// Adding callback function into argumentfunc.call(this,...args);// Calling the findSum() function})}}const getSumPromise =promisifyFunc(findSum)getSumPromise(5,10).then((message)=>{
output.innerHTML = message;}).catch((err)=>{
output.innerHTML = err;})</script></body></html></code></pre>
Output
15,The sum of numbers is 15
The above code looks complex, but if you use it to handle the nested callback functions, it becomes easy to manage them. Here, you can pass custom callback functions to the particular function inside the promise.
Microtasks in JavaScript are small functions that are executed after the completion of the function or program code that creates them and if the JavaScript execution stack is empty. Microtasks are executed before any macrotasks, such as setImmediate() and setTimeout(). Microtasks are used to implement features such as promises.
JavaScript is a single-threaded programming language. However, you can use the promises, callbacks, and asynchronous functions to run the JavaScript code in parallel.
JavaScript runs the code based on the event loop. The event loop is responsible for executing the code, processing it, collecting the event data, and executing the sub-tasks.
Let’s understand the JavaScript event loop first.
JavaScript Event Loop
The event loop executes the JavaScript code line-by-line. It adds the code to the call stack, a queue to execute it.
JavaScript contains two types of queues to execute the tasks.
Micro tasks queues
Macro tasks queues
When the call stack queue is empty, the event loop executes all tasks inside the microtask queue. After that, it executes all functions and code in the Macro task queue.
We will understand more about the JavaScript code execution after understanding the micro and macro tasks.
What is Microtasks in JavaScript?
In JavaScript, a microtask is a shorter function that is produced by the promise, or asynchronous function, and consumed later.
Here is the list of Micro tasks.
Promise callback
Queue MicroTasks
Whatever callback function you pass as an argument of the then(), catch(), or finally() method while consuming the promise code it gets added into the microtask queue.
First, the JavaScript run engine executes the whole script, adds code from the main thread to the call stack, and micro-tasks into the microtask queue. When the execution of all tasks of the call stack is completed, it completes the execution of all tasks in the microtask queue.
Let’s understand it via the example below.
Example
In the code below, we print the start message at the start of the script and the end message at the end of the script.
In the middle, we have defined the promise, which gets resolved immediately. After that, we consumed the promise using the then() method and printed the message returned by the promise.
Open Compiler
<html><body><div id ="output"></div><script>const output = document.getElementById("output");
output.innerHTML +="The start of the code execution. <br>";// Creating the promiselet promise =newPromise(function(resolve, reject){resolve("The promise is resolved. <br>");});// Consuming the promise code
promise.then(function(result){
output.innerHTML += result;});
output.innerHTML +="The end of the code execution. <br>";</script></body></html></code></pre>
Output
The start of the code execution.
The end of the code execution.
The promise is resolved.
The interesting thing is happening in the output of the above code.
In the output, you can see that it prints the start, end, and promise messages at last.
Now, the question is why it happened. The answer is that the callback function of the then() method is added to the microtask queue, and it gets executed only if the call stack is empty.
What is Macrotaks?
Now, let's understand what Macrotaks is.
The Macrotasks are also a short function that gets executed after the execution of all code, which is inside the call stack and microtask queue.
JavaScript run-time engine adds the macro tasks into the microtask queue.
The callback functions produced by the below methods get added to the Macrotask queue.
setTimeout
setInterval
setImmediate
Let's understand the Macrotaks via the example below.
Example
In the code below, we have added the start message, setTimeOut() method, and end message.
In the setTimeOut() method, we have passed the callback function as a first argument, printing the message in the output, and set 0 seconds delay.
Open Compiler
<html><body><div id ="demo"></div><script>let output = document.getElementById("demo");
output.innerHTML +="The start of the code execution.<br>";setTimeout(function(){
output.innerHTML +="The code execution is being delayed for 0 seconds. <br>";},0);
output.innerHTML +="The end of the code execution.<br>";</script></body></html></code></pre>
Output
The start of the code execution.
The end of the code execution.
The code execution is being delayed for 0 seconds.
The output of the above code is also interesting.
It prints the start message first, the end message after that, and the message from the setTimeOut() method at the end.
Here, we set the 0 delay for the setTimeOut() method. Still, it gets executed at the end because the JavaScript run engine adds the callback function in the macro task queue.
Let's understand the microtask and macro tasks together via the example below.
Example
In the code below, we have added the setTimeOut() method with 0 delay, and the callback function prints the message.
After that, we defined a promise using the Promise() constructor and consumed the promise code using the then() method.
At last, we have printed the end method.
Open Compiler
<html><body><div id ="output"></div><script>let output = document.getElementById("output");
Start
End
In Promise constructor.
In setTimeOut() method.
Lets understand the output of the above example.
First, it prints the start message due to the JavaScript call stack.
After that, it adds the callback function of the setTimeOut() method into the Macrotask queue.
Next, it adds the callback function of the then() method into the Microtask queue.
Next, it executes the last line of the code and prints the End message.
Now, the call stack is empty. So, it executes all tasks which are in the Microtask queue. So, it completes the execution of the callback function of the then() method.
Now, the call stack and Microtask queue are both empty. So, it executes all the tasks in the Macrotask queue and completes the execution of the callback function of the setTimeOut() method.
This chapter has demonstrated how the JavaScript run engine executes the code. If you want to change the execution order of the code, you can be careful about using the micro and macro tasks.
The JavaScript functions defined with the async/await keyword can perform the same task as promises with fewer lines of code, and it makes the code readable. The promise’s syntax is a bit complex, so the async/await syntax is introduced.
To use async/await, we need to define an aync function first. For this we write async before function definition. An async function returns a promise. The await keyword is used inside an async function only. The await keyword makes JavaScript to wait for the promise to resolve before continuing the function.
Let’s understand the async/await keywords in details taking them separately −
The JavaScript Async Keyword
A JavaScript function defined with the async keyword is called the asynchronous function. The async function allows you to produce the asynchronous code.
It always returns the promise. If you don’t return the promise manually and return the data, string, number, etc., it creates a new promise and resolves that promise with the returned value.
Syntax
You could use the syntax below to define a function using the async keyword in JavaScript −
asyncfunctionfunc_name(parameters){// function body}
In the above syntax, we have used the ‘async’ keyword before the function name.
Parameters
Func_name − It is a valid identifier for the function name.
Parameters − It takes multiple parameters, the same as a regular function.
Look at the below asynchronous function, returning the ‘hello world’ text. It returns the promise with the ‘hello world’ success message.
You can use the then() and catch() methods to solve the promise returned from the asynchronous function.
Example
We return the text from the getText() function in the code below.
After that, we use the then() and catch() method with the execution of the getText() method to consume the promise returned by the getText() function.
Here, you can observe that we have returned text from the asynchronous function, but it is returning the promise.
Open Compiler
<html><body><div id ="output"></div><script>asyncfunctiongetText(){return"Text from the getText() function.";}getText().then((text)=>{
document.getElementById('output').innerHTML = text +"<br>";}).catch((err)=>{
document.getElementById('output').innerHTML +=JSON.stringify(err);});</script></body></html></code></pre>
Output
Text from the getText() function.
JavaScript Await Keyword
You can use the await keyword inside a JavaScript asynchronous function only. It pauses the execution of the function until the promise gets settled, which means it is either rejected or fulfilled.
Syntax
Following is the syntax to use the await keyword inside an asyn function in JavaScript −
asyncfunctionfunc_name(parameters){await promise;// Function body}
In the above syntax, we have used the await keyword inside the async function.
Example
We have defined the solvePromise() async function in the code below. We have created the new promise using the Promise() constructor in the function. After that, we used the await keyword with the promise to resolve it rather than using the then() or catch() method.
In the output, you can observe that it prints the fulfillment message.
Open Compiler
<html><body><div id ="output">The resultant value from the promise is:</div><script>asyncfunctionsolvePromise(){const promise =newPromise((resolve, reject)=>{resolve('Promise is solved');})const result =await promise;
The resultant value from the promise is: Promise is solved
Example (Waiting for Timeout)
In the code below, we set the timeout of 2000 milliseconds using the setTimeOut() method to resolve the promise.
After that, we used the await keyword with a promise to pause the execution of the function until the promise is settled. In the output, you can see that it prints the message returned from the promise after 2 seconds.
Open Compiler
<html><body><div id ="output">The promise is being solved <br></div><script>asyncfunctionsolvePromise(){const promise =newPromise((resolve, reject)=>{setTimeout(()=>{// Setting up timeout for promisesresolve('The promise is solved after 2 seconds');},2000);})const result =await promise;
The promise is being solved
The promise is solved after 2 seconds
Error Handling with JavaScript Async/Await
While consuming the promise, we used the then() and catch() methods to handle the data and errors.
With the asynchronous function, you can use the trycatch block to handle the errors.
When the promise is fulfilled successfully, the control executes the remaining code of the try block. Otherwise, it executes the code of the catch block to fix the errors.
Syntax
Following is the syntax to handle errors in the asynchronous function −
try{const result =await promise;// Manipulate data}catch(err){// Handle errors}
We need to consume the promise in the try block and handle the errors in the catch block. The catch() method also takes the err as a parameter, which is a promise rejection message or an error object.
Example
In the code below, we have defined a promise and rejected it.
After that, we consume the promise in the try block. As the promise is rejected, the execution control will go into the catch block and print the rejection message.
Open Compiler
<html><body><div id ="demo"></div><script>let output = document.getElementById('demo');asyncfunctionsolvePromise(){const promise =newPromise((resolve, reject)=>{reject("The promise is rejected");})try{const result =await promise;
output.innerHTML +="Inside the try block. <br>";
output.innerHTML += result;}catch(err){
output.innerHTML +="Inside the catch block. <br>";
output.innerHTML += err;}}solvePromise();</script></body></html></code></pre>
Output
Inside the catch block.
The promise is rejected
JavaScript Async Class Methods
You can also define the asynchronous class methods using the async keyword to handle the asynchronous operations.
It has the same syntax as the asynchronous function.
Syntax
Following is the syntax to use the async/await with class methods in JavaScript −
asyncmethod_name(){returnawait promise;}
In the above syntax, method_name is an identifier for the class method, and it uses the async/await keyword to make the method asynchronous.
You can consume the promise returned by the method using the then() and catch() methods.
Example
In the below code, we have created the animal class.
The animal class contains the getAnimalName() method and returns the Lion text. We have used the await keyword before the Lion string, which pauses the execution of the method until the string is created. However, you can also return the promise.
After that, we use the then() method to consume the promise and print the animal name in the output.
Open Compiler
<html><body><div id ="output"></div><script>classanimal{asyncgetAnimalName(){returnawait"Lion";}}const lionObj =newanimal();
lionObj.getAnimalName().then((data)=>{
document.getElementById('output').innerHTML ="The animal name is: "+ data;})</script></body></html></code></pre>
Output
The animal name is: Lion
Real-time Example of JavaScript Async/Await
The above examples are basic examples to demonstrate the use of the async/await keywords in JavaScript.
Lets understand how to use the async/await in real-time development.
Example
In the code below, when the user clicks the button, it calls the getData() function.
The getData() function is an asynchronous function. We used the trycatch block inside the function to handle errors.
In the try block, we used the fetch() API to fetch the data from the API and used the await keyword.
After that, we used the json() method with the response to convert into the JSON and used the await keyword with that.
Next, we print the data.
Also, we print the error message in the catch() method.
Open Compiler
<html><body><button onclick ="getData()">Get Data</button><div id ="demo"></div><script>let output = document.getElementById('demo');asyncfunctiongetData(){try{let response =awaitfetch('https://api.github.com/users');// Pauses the execution until it gets the datalet data =await response.json();// Pauses the execution until it converts the data into json
A JavaScript promise is an object that represents the completion or failure of an asynchronous operation. It employs callback functions to manage asynchronous operations, offering a easier syntax for handling such operations more easily.
A promise object can created using the Promise() constructor. The promise constructor takes a callback function as an argument. The callback function accepts two functions, resolve() and reject(), as arguments. The resolve function is called if the promise returns successfully. The reject function is called when taks fails and returns the reason.
Lets understand how to create promises in JavaScript.
Producing the Promise Code
Syntax
Follow the syntax below to create a promise using the Promise() constructor.
let promise =newPromise(Callback);// Producing the codeORlet promise =newPromise(function(resolve, reject){// Callback function body});
The Promise() constructor takes the callback function as a parameter. Creating the promise is also called code producing. Sometimes, you get promises returned by methods like fetch().
Parameters
The Promise() constructor takes only a single argument.
Callback − It is a callback function to fulfill the promise.
The callback function takes two parameters.
Resolve − You can use the resolve() function to return the successful response from the promise.
Reject − You can use the reject() function to reject the promise and return the error from the promise.
States of the Promise
There are 4 states of the Promise.
Promise.state
Description
Promise.result
Fulfilled
When a promise is completed with a successful response.
Resultant data
Rejected
When a promise is failed.
An error object
Pending
When a promise is pending to execute.
Undefined
Settled
When a promise is either fulfilled or rejected successfully.
Either result data or an error object
The state and result are the properties of the Promise object.
Promise Consumers of JavaScript
In the above section, we discussed how to produce the promise code. If you print the promise on the web page, it will show you [Object Promise].
Lets learn it via the example below.
Example
In the below code, we have used the Promise() constructor to define an instance of the Promise object.
In the callback function, we resolve the promise if the value of the num variable is 10. Otherwise, we reject the promise.
You can observe the promise1 in the output, it prints [Object Promise].
Open Compiler
<html><body><div id ="output">The promise1 object is:</div><script>var num =10;const promise1 =newPromise((resolve, reject)=>{if(num ==10){resolve('The value of the number is 10 <br>');}else{reject('The value of the number is not 10 <br>');}});
To overcome the problem in the above example and get the resultant data from the promise, you are required to consume the promise code.
You can use the below methods with the promise object to consume the promise code.
then() method
catch() method
Lets learn to use both methods to consume the promise code.
JavaScript Promise then() Method
You can use the then() method with an instance of promise to consume its code. With promises, you can get the resultant data or error object using the then() method.
Syntax
You can follow the syntax below to use then() method to consume the promise code.
promise.then(successFunc, errorfunc);
In the abvoe syntax, promise is an instance of the Promise object.
Parameters
successFunc − It is a function that will be executed when the promise is fulfilled.
errorFunc − It is a function that will get executed when the promise is rejected.
Example
The example below contains the same code as the previous example. The main difference is that we have used the then() method to consume the code of the promise.
The promise will be fulfilled as the value of the num variable is 10. We passed the successFunc()and errorfunc() functions as an argument of the then() method.
In the output, you can observe that it executes the successFunc() function as the promise gets fulfilled.
Open Compiler
<html><body><div id ="output"></div><script>const num =10;const promise1 =newPromise((resolve, reject)=>{if(num ==10){resolve('The value of the number is 10 <br>');}else{reject('The value of the number is not 10 <br>');}});
In the below code, we reject the promise if the value of the num variable is not equal to 20. Also, we used the setTImeOut() method to reject the promise after the delay of 2000 milliseconds.
In the output, you can observe that then() method executes the errorfunc() function as the promise is rejected.
Open Compiler
<html><body><div id ="output"></div><script>var num =10;let promise1 =newPromise((resolve, reject)=>{if(num ==20){resolve('The value of the number is 20 <br>');}else{setTimeout(()=>{reject('The value of the number is not 20 <br>');},2000);}});
output.innerHTML +="Wait for consuming the promise <br>";
promise1.then(successFunc, errorfunc);functionsuccessFunc(message){
document.getElementById('output').innerHTML += message;}functionerrorfunc(message){
document.getElementById('output').innerHTML +="Error: "+ message;}</script></body></html></code></pre>
Output
Wait for consuming the promise
Error: The value of the number is not 20
JavaScript Promise catch() Method
The catch() method of Promise instance allows you to catch the error. If any error occurs while settling the promise, the control flow comes into the catch() method.
Syntax
You can follow the syntax below to use the catch() method with promises.
promise
.then(successFunc).catch(errorFunc);
We used the then() and catch() methods with promise in the above syntax.
You can see that we have passed only the single function to the then() method. So, it will handle the success response, and the catch() method will handle the error response.
Parameters
errorFunc − The errorFunc() callback function will be executed when the promise is rejected.
Example
In the code below, we have created a promise using the Promise() object, and we have rejected the promise.
While consuming the promise, we used the then() and catch() method. In the output, you can see that control goes into the catch() method directly, as we have rejected the promise.
Open Compiler
<html><body><div id ="output"></div><script>var num =10;const promise =newPromise((resolve, reject)=>{reject("Promise is rejected!");});
The finally() method of the promise object can be used with the instance of the Promise object. The code of the finally() method always gets executed when the promise is fulfilled.
Syntax
Users can follow the syntax below to use the finally() method with promise.
In the above syntax, we have used the then(), catch(), and finally() methods with promise.
Parameters
Callback − It is a callback function that will always be executed when a promise is settled.
Example
In the code below, we have defined the promise and resolved it.
Also, we used the finally() method while consuming the code of the promise. In the output, you can observe that the JavaScript control first goes into the then() method and then goes to the finally() method.
Open Compiler
<html><body><div id ="demo"></div><script>let output = document.getElementById('demo');const num =10;const promise =newPromise((resolve, reject)=>{resolve("Promise is resolved successfully!");});
promise
.then((message)=>{
output.innerHTML +="Inside the then() method. <br>";
output.innerHTML += message;}).catch((message)=>{
output.innerHTML +="Inside the catch() method.<br>";
output.innerHTML += message;}).finally(()=>{
output.innerHTML +="<br>Inside the finally() method.";});</script></body></html></code></pre>
Output
Inside the then() method.
Promise is resolved successfully!
Inside the finally() method.
The callback function of the finally() method is also executed even if the promise is rejected.
JavaScript Promise Reference
JavaScript Promise Constructor
You can call the Promise() constructor using the new keyword.
Constructor
Description
Promise()
It is used to create an instance of the Promise object.
JavaScript Promise Properties
Here, we have listed the properties of the Promise object.
Property
Description
constructor
To get the promise constructor function for the instance of the Promise object.
JavaScript Promise Methods
Static Methods
The static methods can be called by taking the Promise as a reference.
Method
Description
all()
To handle multiple promises. It takes the array of promises as an argument.
allSettled()
To get a promise when all promises are settled.
any()
It returns the single promise that is fulfilled earliest.
race()
To get a single promise from the iterable of promises.
reject()
To reject a promise with a reason.
resolve()
To fulfill the promise with data or reason.
Instance Method
The instance methods can be called by taking the instance of the Promise object as a reference.
Method
Description
catch()
To handle the error.
then()
To handle the resultant data and error.
finally()
It gets called when the promise is settled (fulfilled or rejected).
The callback function in JavaScript is regularly passed as an argument of another function. Dont consider the callback as a name or keyword here. The callback function name can be any valid identifier.
The callback function can be called inside the parent function after completing the particular task in the parent function. It is mainly used to handle the asynchronous operations.
Syntax
You can follow the syntax below to use the callback functions.
functionfunc_name(callback){// function bodycallback();}func_name(callback);// Function invocationORfunc_name(()=>{// Callback function body})
In the above syntax, we have passed the callback as an argument of the func_name() function.
As shown in the above syntax, you can also pass the arrow or anonymous function as a callback function.
Example
In the below code, we have passed the multiply() function as an argument of the sum() function.
In the sum() function, we call the callback function at the end.
Open Compiler
<html><body><div id ="output"></div><script>let output = document.getElementById('output');functionmultiply(a){let m = a *4;
output.innerHTML ="The result is "+ m +".<br>";}functionsum(a, b, callback){let c = a + b;callback(c);// Invoking the callback funciton}sum(4,8, multiply);// Passing multiply function as a callback</script></body></html></code></pre>
Output
The result is 48.
Passing the anonymous function as a callback
Example
In the code below, we have defined the mathOperations() function, which takes the callback function as an argument.
We call the callback function inside the mathOperations() function and get its returned value.
While calling the mathOperations() function, we have passed the different anonymous functions as an argument. This way, you can control which function you want to execute inside the particular function using the callback functions.
Open Compiler
<html><body><div id ="output"></div><script>let output = document.getElementById('output');functionmathOperation(a, b, callback){let result =callback(a, b);
output.innerHTML +="The result is "+ result +".<br>";}mathOperation(10,20,function(a, b){return a + b;// Callback function to add numbers});mathOperation(20,10,function(a, b){return a - b;// Callback function to subtract numbers});mathOperation(10,20,function(a, b){return a * b;// Callback function to multiply numbers});</script></body></html></code></pre>
Output
The result is 30.
The result is 10.
The result is 200.
Need for the Callback Function
Now, lets understand the need for callback functions in real-time development.
JavaScript is a single-threaded programming language. So, it executes the code line-by-line. When you need to fetch the data from API, load images, or perform any asynchronous operations, it can take time and block the execution of the other code.
In such cases, you can use the callback function to execute the code, which must be executed after the asynchronous operation, and you can execute the other code without blocking it.
For example, you are making an API request and need the API data for validation purposes. So, you can perform the data validation in the callback function and continue running other tasks.
Lets understand it using the setTimeOut() method.
Example
In the below code, we use the setTimeOut() method to write the asynchronous code.
It executes the printMessage() function after the delay of the 500 milliseconds. We have passed the printMessage() function as a callback of the setTimeOut() method.
In the output, you can observe that the script runs without blocking, and it executes the printMessage() function after 500 milliseconds.
Open Compiler
<html><body><div id ="output"></div><script>let output = document.getElementById('output');
output.innerHTML +="Start of the program. <br>";setTimeout(printMessage,500);// Asynchronous codefunctionprintMessage(){
output.innerHTML +="In the printMessage() function. <br>";}
output.innerHTML +="End of the program. <br>";</script></body></html></code></pre>
Output
Start of the program.
End of the program.
In the printMessage() function.
Callback Function with built-in Methods
Many built-in JavaScript method takes the callback function as an argument to execute the custom JavaScript code once the execution of the method is finished.
Here, we will look at 2 to 3 built-in methods, which take the callback function as an argument with examples.
JavaScript array.sort() method with a callback function
The array.sort() method is used to sort the array element. It sorts the array elements in ascending order by default. If you want to sort the array elements in descending order or any custom order, you can pass the callback function as an argument.
Syntax
Follow the syntax below to use the array.sort() method
arr.sort(callback);
The array.sort() method optionally takes the callback function as an argument. The callback function should return 0, 1, or -1.
Example
In the below code, we have defined the array containing the numeric values. First, we have used the sort() method without a callback function. You can see that it sorts the array in the ascending order.
After that, we passed the anonymous function as a callback function of the sort() method. The callback function returns the difference between element b and a to sort the array in descending order.
Open Compiler
<html><body><div id ="output"></div><script>let output = document.getElementById('output');let arr =[23,21,56,11,10,7,8];
output.innerHTML +="The sorted array is - "+ arr.sort();// Sorting array in descending orderlet sorted = arr.sort(function(a, b){return b - a;});
output.innerHTML +="<br>The sorted array in descending order is - "+ sorted;</script></body></html></code></pre>
Output
The sorted array is - 10,11,21,23,56,7,8
The sorted array in descending order is - 56,23,21,11,10,8,7
JavaScript array.filter() method with the callback functions
The array.filter() method is used to filter the array elements. It takes the callback function as an argument. If the callback function returns true, it filters the element. Otherwise, it skips the array element.
Syntax
Follow the syntax below to use the array.filter() method.
Array.filter(callback);
The callback function must return the boolean value.
Example
In the below code, we have passed the filterCallback() function as a callback of the filter() method. The filterCallback() function returns the boolean value if the number is even.
At last, you can see the filtered even number in the output.
Open Compiler
<html><body><div id ="output"></div><script>let output = document.getElementById('output');let arr =[23,21,56,11,10,7,8];let eventNums = arr.filter(filtercallback);functionfiltercallback(element){return element %2==0;}
output.innerHTML +="The original array is: "+ arr +"<br>";
output.innerHTML +="The even numbers are: "+ eventNums;</script></body></html></code></pre>
Output
The original array is: 23,21,56,11,10,7,8
The even numbers are: 56,10,8
Callback Function with Events
You can use the addEventListner() method in JavaScript to listen for the event. The addEventListener() method takes the callback function as a second parameter.
It executes the callback function whenever a specified event gets triggered on the web page.
Syntax
Follow the syntax below to use the addEventListener() method.
Element.addEventListener(event, callback);
In the above syntax, an event is a string representing the event's name, and a callback is a function that should be executed when an event triggers.
Example
In the below code, we have created the button.
In JavaScript, we accessed the button using its id and added the click event.
Whenever the user clicks the button, it will print the message.
Open Compiler
<html><body><button id ="btn"> Click Me </button><p id ="output"></p><script>let output = document.getElementById('output');let button = document.getElementById('btn');
button.addEventListener('click',function(){
output.innerHTML ='You have clicked the button. <br>';});</script></body></html></code></pre>
Output
Nesting Callbacks and Callback Hell
You can have nested callback functions like the nested loop or if-else statement in JavaScript. If the first function is dependent on the data of the second function, and the second function is dependent on the data of the third function, you may require the nested callback function.
Lets understand it via the example below.
Example
The asyncTask() function completes the tasks in the below code and calls the callback function passed as an argument.
After that, we called the asyncTask() function and passed the callback function as a third argument. In the callback function, we have called the asyncTask() function again and passed the callback function as a third argument.
In this way, we have used the callback functions at 3 nested levels.
Open Compiler
<html><body><div id ="output"></div><script>let output = document.getElementById('output');functionasyncTask(taskName, duration, callback){
Asynchronous JavaScript is a programming technique that enables your program to start a potentially long-running task and continue to executing other tasks parallelly. JavaScript is a single-threaded programming language. It means you can execute a single script or particular code at a time. JavaScript control flow moves the line by line and executes each line of code.
We can implement asynchronous operations in our JavaScript programs using callback functions, promises, async/await etc. The callback functions are functions passed as arguments to other functions. The promises are objects representing the success of failure of an asynchronous operation. The async/await syntax is simple implementation of promises. We will discuss these approaches in details in respective chapters.
To perform the multiple tasks parallelly, you need asynchronous JavaScript.
Lets understand what synchronous JavaScript is before understanding asynchronous JavaScript.
What is Synchronous JavaScript?
The Synchronous JavaScript executes the JavaScript code line-by-line. The control flow moves from top to bottom and runs each statement one by one.
Lets understand it via the example below.
Example
The control flow for the code is given below.
It calls the test1() function.
In the test1() function, it prints the start message.
Next, it calls the test2() function.
The test2() function prints the start and end messages.
After that, it prints the end message in the test1() function.
End of the code execution.
Open Compiler
<html><body><div id ="demo"></div><script>let output = document.getElementById('demo');functiontest2(){
It creates a call stack, adds the code to it, and executes the code in the last in, first out (LIFO) order.
Now, lets understand that what is the asynchronous JavaScript.
What is Asynchronous JavaScript?
Asynchronous JavaScript enables simultaneous code execution. You can use asynchronous JavaScript to make your application multi-threaded. It allows you to perform time-consuming or expensive tasks together.
Lets understand the Asynchronous JavaScript via the example below.
Example
The execution flow of the code is explained below.
It prints the start message.
After that, it prints the end message without waiting until the execution of the setTimeOut() method is finished.
At last, it executes the code of the setTimeOut() method.
Open Compiler
<html><body><div id ="demo"></div><script>let output = document.getElementById('demo');
By writing the asynchronous JavaScript code, you can execute another JavaScript code without waiting to finish the execution of the particular code.
Why Do We Need Asynchronous JavaScript?
In the above section, we have learned to write the asynchronous JavaScript code via simple example. But the question is when you need to write the asynchronous JavaScript code as you dont need to perform simple tasks like printing the messages.
Lets understand it via the example below.
Example
In the below code, we find the first 10 lakh prime numbers. For that, we traverse through numbers and check whether the number is prime using the checkForPrime() function.
In the code, you can click the generate prime button. The code will start finding the first 10 lakh prime numbers. After that, you can immediately click the print message button to print the message. You can observe that the web page is responsive and does not print any message.
However, it will print the message once the execution of the getPrimes() function is finished.
So, it is necessary to complete such time-expensive tasks parallelly. Otherwise, it makes the web page unresponsive.
Open Compiler
<html><body><button onclick ="getPrimes()"> Generate primes </button><button onclick ="printMessage()"> Print Message </button><div id ="demo"></div><script>let output = document.getElementById('demo');// Function to check whether the number is a prime numberfunctioncheckForPrime(num){for(let p =2; p <= Math.sqrt(num); p++){if(num % p ===0){// Check whether the number is divisible by preturnfalse;}}return num >1;}functiongetPrimes(){const primeNums =[];// Array to store prime numberslet p =1;while(primeNums.length <1000000){// Find first 10 lakh prime numbersif(checkForPrime(p)){
primeNums.push(p);}
p++;}
output.innerHTML +="The execution of the getPrime() function is completed. <br>";}functionprintMessage(){// Function to print the message
output.innerHTML +="Button is clicked! <br>";}</script></body></html></code></pre>
Output
Real-time Use Cases of Asynchronous JavaScript
Here are the real-time use cases of asynchronous JavaScript.
Fetching data from API
When you fetch data from the API, it takes time to get the data according to the server's response time. So, you can use the asynchronous JavaScript to continue the execution of the other code without waiting for the API response.
Loading external resources
Sometimes, it happens that you need to load multiple libraries, external scripts, images, etc., into the application. The web page doesnt allow you to interact with the web page without loading all external resources. So you can load the external resources asynchronously.
Task scheduling
You can use asynchronous JavaScript to schedule the tasks using the setTimeOut() method or perform tasks after a particular interval using the setInterval() method.
Data validation
Sometimes, developers are required to do data validation. You can perform such tasks in the background or parallel with other codes.
File uploads
If you allow users to upload large files, it may take time to upload according to users' internet speed. So you can execute the file uploading asynchronously.
Data caching
The data caching is one of the most important features of the application to increase the performance and may take time according to the data size. So, you can use the promises to cache the data asynchronously.
The ECMAScript 2022 standard was released in 2022. Important features added to this update include private methods and fields, Array at() and String at() methods etc. This chapter discuss all the newly added features in ECMAScript 2022.
New Features Added in ECMAScript 2022
Here are the new methods, features, etc., added to the ECMAScript 2022 version of JavaScript.
Array at() Method
String at() Method
Private methods and fields
Object.hasOwn()
error.cause
await import
Here, we have explained each feature in detail.
Array at() Method
ECMAScript 2022 (ES2022) introduced Array at() method to arrays. In JavaScript, array at() method used to access the array element from the particular index. You can’t use the negative index in the arr[index] representation, but with the array.at() method, you can also use the negative index to access array elements.
When you use the negative index, it returns the array from the last.
Example
In the below code, we access the last and third-last elements from the array using the negative indexes and array.at() method.
Open Compiler
<body><div id ="demo1">The last array element is:</div><div id ="demo2">The third last array element is:</div><script>const arr =[10,20,60,72,6,12,23];
The last array element is: 23
The third last array element is: 6
String at() Method
ECMAScript introduced String at() method to strings. In JavaScript, the String at() method is used to access the characters from the particular string index. It also accepts the negative index as an argument.
Example
In the code below, we access the last and fourth last characters from the string using the negative indexes and string.at() method.
Open Compiler
<html><body><div id ="demo1">The last string character is:</div><div id ="demo2">The fourth last string character is:</div><script>let str ="Hello world";
The last string character is: d
The fourth last string character is: o
Private Methods and Fields
ECMAScript 2022 introduced the way to write private methods and fields. In JavaScritp, you can write the field name or method name followed by the hash sign ('#') to make them private. You can't access the private fields and methods using the class instance. However, you can access them inside the class.
Example
In the below code, the car class contains the 'brand' private field and the 'carBrand' private method. The getBrand() method is public.
We have created the instance of the car class and invoked the getBrand() method using it. The getBrand() method calls the carBrand() method.
Open Compiler
<html><body><div id ="output"></div><script>classcar{
#brand;constructor(brand){this.#brand = brand;}getBrand(){returnthis.#carBrand();}#carBrand(){return"The car brand is "+this.#brand;}}constBMW=newcar("BMW");
document.getElementById("output").innerHTML =BMW.getBrand();</script></body></html></code></pre>
Output
The car brand is BMW
Object hasOwn() Method
The Object.hasOwn() method is a replacement for the Object.hasOwnProperty() method. It is used to check whether the object contains a particular property.
Example
In the code below, we use the hasOwn() method to check whether the obj object contains the name property.
Open Compiler
<html><body><div id ="output"></div><script>const obj ={
name:"sam",
age:50,}
document.getElementById("output").innerHTML ="Does obj contain name property? "+ obj.hasOwnProperty("name");</script></body></html></code></pre>
Output
Does obj contain name property? true
The error.cause Property
The 'cause' is a property of the JavaScript object. It represents the reason for the error. It is introduced in ECMAScript 2022.
Example
In the below code, we throw a new error from the 'try' block. Also, we specify the reason for the error using the cause property.
We access the 'cause' property value in the catch block to know the reason.
Open Compiler
<html><body><div id ="demo"></div><script>let output = document.getElementById("demo");try{
output.innerHTML +="Inside the try block <br>";thrownewError("New error",{ cause:"Testing with error."})}catch(error){
output.innerHTML +="The reason for the error is: "+ error.cause +"<br>";}</script></body></html></code></pre>
Output
Inside the try block
The reason for the error is: Testing with error.
The Await Import
You can use the asynchronous import to import the dynamic modules. You need to use the 'await' keyword for the asynchronous import.
For example, the below code contains the self-invoking asynchronous function. Also, the 'await' keyword is used inside the function to await the import.
The ECMAScript 2021 standard was released in 2021. ECMAScript 2021 brought many notable features to JavaScript. The introduction of the String replaceAll() method simplified global string replacement. Logical Assignment Operators, (&&=, ||=, and ??=), enhanced code conciseness. This update focused on improving developer productivity and code readability.
This chapter will discuss all the newly added features in ECMAScript 2021.
New Features Added in ECMAScript 2021
Here are the new methods, features, etc., added to the ECMAScript 2021 version of JavaScript.
Numeric Separators (_)
Promise any() method
String replaceAll() method
Logical AND Assignment Operator (&&=)
Logical OR Assignment (||=)
Nullish Coalescing Assignment (??=)
Here, we have explained each feature in detail.
Numeric Separators (_)
ECMAScript 2021 introduced numeric separators. The numeric seprators are used to make the number more readable.
Example
We added a numeric separator in the code below to make the number more readable.
Open Compiler
<html><body><div id ="output">The value of the num is:</div><script>let num =90_00_000;
ECMAScript 2021 introduced Promise any() method. The promise.any() method fulfills any promise from the array of promises, which resolves at the earliest.
Example
In the below code, we have created multiple promises and passed them as an argument of the Promise.any() method.
We have resolved the promise1 and rejected the promise2. For the Promise.any() method, JavaScript control goes into the then() block as promise1 gets resolved.
Promise.any(promises).then(()=>{
output.innerHTML +='One or more promises are resolved!';}).catch((err)=>{
output.innerHTML +='All promises are rejected:'+ err;});</script></body></html></code></pre>
Output
One or more promises are resolved!
String replaceAll() Method
The ECMAScript 2021 introduced String replaceAll() method to the Strings. The string replaceAll() method is used to replace the particular substring with another substring.
The replaceAll() method takes either string or regular expression as a parameter.
Example
In the below code, we have replaced the lowercase 'a' with the uppercase 'A' using the replaceAll() method.
Open Compiler
<html><body><div id ="output1">Original string is:</div><div id ="output2">Updated string is:</div><script>let str ="abcd abcd abcd abcd";
Original string is: abcd abcd abcd abcd
Updated string is: Abcd Abcd Abcd Abcd
Logical AND Assignment Operator (&&=) Operator
ECMAScript 2021 introduced the logical assignment operators (&&=, ||= and ??=) to the operators. The JavaScript logical AND Assignment operator updates the value of the first operand with the second operand if the first operand is true.
Example
In the code below, the str string's value is not falsy. So, it updates the value of an str variable with 'Hi'.
Open Compiler
<html><body><div id ="output">The value of the str is:</div><script>let str ="Hello";
ECMAScript 2021 introduced the logical OR Assignment operator to operators. It updates the value of the first operand with the second operand if the first operand is false.
Example
In the code below, the initial value of the str is false. So, the Logical OR assignment operator updates its value with the second operand, which is 10.
Open Compiler
<html><body><div id ="output">The value of the str is:</div><script>let str =false;
The ECMAScript 2021 introduced the nullish coalescing assignment operator to operators. This operator updates the value of the left operand if it is undefined or null.
Example
In the below code, the value of the str variable is null. So, the nullish coalescing assignment operator assigns the 'default' value to the str variable.
Open Compiler
<html><body><div id ="output">The value of the str is:</div><script>let str =null;
The ECMAScript 2020 version of JavaScript was released in 2020. Notable features added in this version include the nullish coalescing operator (??) for more concise default value assignment and dynamic import() for on-demand module loading. BigInt provides a way to safely work with very large integers. This chapter will discuss all the newly added features in ECMAScript 2020.
Features Added in ECMAScript 2020
Here are the new methods, features, etc., added to the ECMAScript 2020 version of JavaScript.
BigInt
Promise allSettled()
String matchAll()
The Nullish Coalescing Operator (??)
The Optional Chaining Operator (?.)
Here, we have explained each feature in detail.
BigInt Primitive DataType
The ECMAScript 2020 introduced BigInt to the primitive data types. You can use the Big Int when you need to store a large number, which cant be represented using the 64-bit representation.
To convert the number into the Big int, you can write the number followed by n.
Example
In the below code, we have defined the number of big int data type.
Open Compiler
<html><body><div id ="output">The number of bigint type is:</div><script>const bigNum =1325461651565143545565n;
The number of bigint type is: 1325461651565143545565
The Nullish Coalescing Operator (??)
The JavaScript Nullish Coalescing operator returns the left operand if it is not undefined or null. Otherwise, it returns the right operand. It is used to set default values to the variables.
Example
In the below code, the left operand for the nullish coalescing operator is undefined. So, it returns the value of the right operand.
Open Compiler
<html><body><div id ="output">The value of the str is:</div><script>let str =undefined??"Hello";
The Promise.allSettled() method returns the status of all promises once all promises get fulfilled.
Example
In the code below, we have defined the array of promises.
After that, we used the promise.allSettled() method to fulfill all promises. In the output, you can see that method returns the array of objects, representing the status and result of each promise.
Open Compiler
<html><body><div id ="output"></div><script>const promises =[
The string matchAll() method matches all occurrences of the particular string substring. It takes the string or regular expression as a parameter.
Example
In the below code, we used the String.matchAll() method to match the abcd substring in the str string. The method returns an iterator of all matching occurrences.
Open Compiler
<html><body><div id ="output">The matching results are:<br></div><script>let str ="Abcd abcd abcd";let matches = str.matchAll('abcd');for(let x of matches){
document.getElementById("output").innerHTML += x +"<br>"}</script></body></html></code></pre>
Output
The matching results are:
abcd
abcd
The Optional Chaining Operator (?.)
The Optional chaining operator is used to access the nested object properties. If any nested object is undefined, it returns undefined rather than throwing an error.
Example
In the code below, the obj object contians the obj1 nested object, containing the name property.
We try to access the obj2 objects name property with an optional chaining operator. Obj2 is not defined here, so it returns the undefined rather than throwing an error.
Open Compiler
<html><body><div id ="output">The name of obj2 is:</div><script>let obj ={
The ECMAScript 2019 standard was released in 2019. Important additions to this update include Array flat() and Array flatMap(), offering concise array manipulation methods. The Object.fromEntries() method simplifies object creation from key-value pairs. These improvements in ECMAScript 2019 aimed to enhance code conciseness and functionality. This chapter will discuss all the newly added features in ECMAScript 2019.
New Features Added in ECMAScript 2019
Here are the new methods, features, etc., added to the ECMAScript 2019 version of JavaScript.
Array.flat()
Array.flatMap()
Revised Array.Sort()
Object.fromEntries()
Optional catch binding
Revised JSON.stringify()
Revised Function.toString()
Separator symbols allowed in string literals
String.trimEnd()
String.trimStart()
JavaScript Array flat() Method
The ECMAScript 2019 introduced Array.flat to the arrays. The JavaScript array flat() method is used to flatten the array by removing the nested array and adding its elements to the original array.
Example
In the code below, we used the array.flat() method to flatten the arr array.
Open Compiler
<html><body><div id ="output">The flatten array is:</div><script>const arr =[1,[10,20],30,[40,[50],60],70];
The ECMAScript 2019 also introduced Array flatMap to arrays. The array flatMap() flatten the array after mapping the array elements with new elements.
Example
In the below code, we return the array of two elements from the callback function of the flatMap() method. After that, the flatMap() method flattens it.
In the output, you can see that 'updated' is a single array. So, it first maps the current element to a new element or array and flattens it.
Open Compiler
<html><body><div id ="output">The updated array is:</div><script>const arr =[2,4,6,8];const updated = arr.flatMap((ele)=>[ele *2, ele *3]);
In ECMAScript 2019, JavaScript array.prototype.sort() method has been revised to make it stable.
Before 2019, the behavior of the sort() method was not consistent in sorting the equal elements. It could not preserve the original order for the same array elements.
Now, array.sort() method is stable as it uses the variation of the merge sort.
Example
In the below code, we have defined the watches array containing multiple objects. Each object of the array contains the brand and price property.
We used the sort() method to sort the array based on the value of the brand property. In the output, you can see that it preserves the original order for the same brand name.
Open Compiler
<html><body><div id ="output">The sorted array elements are:<br></div><script>const watches =[{ brand:"Titan", price:1000},{ brand:"Casio", price:1000},{ brand:"Titan", price:2000},{ brand:"Titan", price:3000}]
watches.sort((a, b)=> a.brand.localeCompare(b.brand))for(let obj of watches){
document.getElementById("output").innerHTML +=JSON.stringify(obj)+"<br>";}</script></body></html></code></pre>
Output
The sorted array elements are:
{"brand":"Casio","price":1000}
{"brand":"Titan","price":1000}
{"brand":"Titan","price":2000}
{"brand":"Titan","price":3000}
JavaScript Object fromEntries
The Object fromEnteries() method allows you to create a new object from the 2-dimensional array. Each element of the array should be an array of length 2, containing the key-value pair for the object.
Example
In the below code, we have defined the 2D array containing the fruit name and price. After that, we used the Object.fromEntries() method to create an object from the array.
Open Compiler
<html><body><div id ="output">The fruits object is :</div><script>const entries =[["Apple",20],["Banana",40],["watermelon",30]];const fruits = Object.fromEntries(entries);
The fruits object is : {"Apple":20,"Banana":40,"watermelon":30}
Optional catch binding
After ECMAScript 2019, you can remove the 'catch' block parameter if you don't need it.
For example, before ECMAScript 2019, you must need the parameters with the catch block.
try{}catch(error){}
After ECMAScript 2019,
try{}catch{}
Revised JSON.stringify()
Before ECMAScript 2019, JavaScript JSON.stringify() method was not able to convert the Unicode characters into a string, but after ES10, it is possible, as shown in the example below.
Example
In the code below, we convert the Unicode character into the JSON string and then use the JSON.parse() method to parse the string.
Open Compiler
<html><body><div id ="output1">The unicode string value is:</div><div id ="output2">The unicode JSON value is:</div><script>let str =JSON.stringify("\u27A6");
The unicode string value is: ""
The unicode JSON value is:
Revised Function toString()
Before ECMAScript 2019, when you used the toString() method with the function, it returned the function's source code without comment, syntax, etc.
After ES10, it returns the function with spaces, syntax, comments, etc.
Example
The toString() method returns the function after converting into the string in the below code. The resultant string contains the spaces, comments, etc.
Open Compiler
<html><body><div id ="output">After converting the function to string is:</div><script>functiontest(){return10*20;}
After converting the function to string is: function test() { return 10 * 20; }
Separator symbols allowed in string literals
After ECMAScript 2019, you can use the separator symbols \u2028 and \u2029)to separate the line and paragraph in the string.
Example
In the below code, we used the Unicode character to separate the line. However, you won't be able to see separating lines directly as we use the innerHTML property to update the HTML.
Open Compiler
<html><body><div id ="output">The string with seprator symbol is:</div><script>let str ="Hi\u2028";