Blog

  • Browser Object Model

    The Browser Object Model (BOM) in JavaScript refers to the objects provided by the browsers to interact with them. By using these objects, you can manipulate the browser’s functionality. For example, you can get the browser history and window size, navigate to different URLs, etc.

    The Browser object model is not standardized. It depends on which browser you are using.

    Here, we have listed all objects of the Browser Object Model with descriptions −

    • Window − The ‘window’ object represents the current browser window. You can use it to manipulate the browser window.
    • Document − The ‘document’ object represents the currently opened web page in the browser window. You can use it to customize the property of the document.
    • Screen − It provides information about the user’s device’s screen.
    • History − It provides the browser’s session history.
    • Navigator − It is used to get the browser’s information like default language, etc.
    • Location − The Location object is used to get the URL information, such as the hostname of the current web page.
    • Console − The console object allows developers to access the browser’s console.

    JavaScript Window Object

    The JavaScript window object represents the browser’s window. We can use different methods and properties of the window object to manipulate current browser window. For example, showing an alert, opening a new window, closing the current window, etc.

    All the JavaScript global variables are properties of window object. All global functions are methods of the window object.

    The other objects listed above such as document, screen, history etc., are the properties of the window object. We can access these objects as properties of the window object. We can also access them with referencing the window object. Look at the below example snippet to access the document object

    window.document.write("Welcome to Tutorials Point");

    or without window object −

    document.write("Welcome to Tutorials Point");

    The innerHeight and innerWidth properties of the window object are used to access the height and width of the browser window. We will learn JavaScript window object in detail in next chapters.

    JavaScript Document Object

    The document object is a property of the JavaScript window object. The whole HTML document is represented as a document object. The document object forms HTML DOM. It is root node of the HTML document.

    The document object can be accessed as window.document or just document.

    The document object provides us with many properties and methods to access the HTML elements and manipulate them. One such method is document.getElementById() to access the HTML element using its id.

    We can access an element with id as “text” using getElementById() method and manipulate it

    Example

    <html><body><div id ="text">This text will be changed.</div><script>// Access the element with id as textconst textDiv = document.getElementById("text");// Change the content of this element
    
      textDiv.innerHTML ="The text of this DIV is changed.";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The text of this DIV is changed.
    

    JavaScript Screen Object

    In JavaScript, the screen object is a property of window object. It provides us with properties that can be used to get the information about the device window screen. We can access the screen object as window.screen or just screen.

    To get the width and height of the device screen in pixels we can use the screen.width and screen.height properties

    Example

    <html><body><div id ="width">Width of the device screen is </div><div id ="height">Height of the device screen is </div><script>
       document.getElementById("width").innerHTML += screen.width +" px.";
       document.getElementById("height").innerHTML += screen.height +" px.";</script><p> The above result may be different for different device.</p></body></html>

    Output

    Width of the device screen is 1536 px.
    Height of the device screen is 864 px.
    The above result may be different for different device.
    

    JavaScript History Object

    In JavaScript, the history object is also a property of the window object. It contains a list of the visited URLs in the current session. The history object provides an interface to manipulate the browser's session history.

    The JavaScript history object can be accessed using window.history or just history. We can use the methods of history object to navigate the URLs in the history list. For example to go the previous page/URL in the history list, we can use history.back() method.

    JavaScript Navigator Object

    The JavaScript navigator object is also a property of the window object. Using the 'navigator' object, you can get the browser version and name and check whether the cookie is enabled in the browser. We can access the navigator object using window.navigator. We can also access it without using the window prefix.

    JavaScript Location Object

    The JavaScript 'location' object contains various properties and methods to get and manipulate the information of the browser's location, i.e. URL. It's also a property of JavaScript window object.

    We can use the properties and methods of the location object to manipulate the URL information. For example, to get the host from the current URL, we can use the window.location.host or just location.host. The host is property of the location object.

    Example

    <html><body><div id ="output"></div><script>
    
      document.getElementById("output").innerHTML ="The host of the current location is: "+ location.host;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The host of the current location is: www.tutorialspoint.com
    

    JavaScript Console Object

    The JavaScript console object allows us to access the debugging console of the browser. It is a property of the JavaScript window object. It can be accessed using window.console or just console.

    The console object provides us with different methods such as console.log(). The console.log() method is used to display the message in debugging console.

    What's Next?

    We have provided detailed information about each of the above objects in separate chapters.

  • Deleting Cookies

    In order to delete cookies with JavaScript, we can set the expires date to a past date. We can also delete a cookie using the max-age attribute. We can delete the cookies explicitly from the browser.

    Deleting cookies with JavaScript removes small bits of data that websites store on a user’s computer. Cookies are used to track a user’s browsing activity and preferences.

    It is important to note that deleting cookies can have unintended consequences. For example, if you delete a cookie that is used to authenticate you to a website, you will be logged out of the website. You should only delete cookies if you are sure that you want to do so.

    Different Ways to Delete the Cookies

    There are three different ways to delete the cookies −

    • Set the past expiry date to the ‘expires’ attribute.
    • Use the ‘max-age’ attribute.
    • Delete cookies explicitly from the browser.

    Delete Cookies using ‘expires’ Attribute

    When you set the past expiry date as a value of the ‘expires’ attribute, the browser automatically deletes the cookie.

    Syntax

    Follow the syntax below to delete a cookie by setting up the past expiry date as a value of the ‘expires’ attribute.

    document.cookie ="data1=test1;expires=Tue, 22 Aug 2023 12:00:00 UTC;";

    In the above syntax, we have set the past date as a value of the ‘expires’ attribute. You may set any past date.

    Example

    In the below code, you can click on the set cookies button to set cookies. After that, click on the get cookies button to observe the cookies.

    Next, click the delete cookies button, and again get cookies to check whether the cookies are deleted.

    Here, we delete the data1 cookie only.

    <html><body><button onclick ="setCookies()"> Set Cookie </button><button onclick ="deleteCookies()"> Delete Cookie </button><button onclick="readCookies()"> Read Cookies </button><p id ="output"></p><script>let output = document.getElementById("output");functionsetCookies(){
    		document.cookie ="data1=test1;";
    		document.cookie ="data2=test2;";}functiondeleteCookies(){
    		document.cookie ="data1=test1;expires=Tue, 22 Aug 2023 12:00:00 UTC;";
    		document.cookie ="data2=test2;expires=Mon, 22 Aug 2050 12:00:00 UTC;";}functionreadCookies(){const allCookies = document.cookie.split("; ");
    		output.innerHTML ="The cookie is : <br>";for(const cookie of allCookies){const[key, value]= cookie.split("=");if(key =="data1"|| key =="data2"){
    
    			output.innerHTML +=${key} : ${decodeURIComponent(value)} &amp;lt;br&amp;gt;;}}}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Delete Cookies using 'max-age' Attribute

    The browser automatically deletes the cookie when you assign 0 or a negative value to the 'maxAge' attribute.

    Syntax

    Follow the syntax below to use the max-age attribute to delete the cookie.

    document.cookie ="user1=sam;max-age=-60;";

    In the above syntax, we have set a negative value to the 'max-age' attribute to delete the cookies.

    Example

    In the below code, we delete the user1 cookie only in the deleteCookies() function.

    <html><body><button onclick ="setCookies()"> Set Cookie </button><button onclick ="deleteCookies()"> Delete Cookie </button><button onclick ="readCookies()"> Read Cookies </button><p id ="output"></p><script>let output = document.getElementById("output");functionsetCookies(){
    		document.cookie ="user1=sam;";
    		document.cookie ="user2=virat;";}functiondeleteCookies(){
    		document.cookie ="user1=sam;max-age=-60;";
    		document.cookie ="user2=virat;max-age=5000;";}functionreadCookies(){const allCookies = document.cookie.split("; ");
    		output.innerHTML ="The cookie is : <br>";for(const cookie of allCookies){const[key, value]= cookie.split("=");if(key =="user1"|| key =="user2"){
    
    			output.innerHTML +=${key} : ${decodeURIComponent(value)} &amp;lt;br&amp;gt;;}}}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Delete Cookies Explicitly from the Browser

    You can manually delete the cookies from the browser by following the steps below.

    Step 1 − In your browser, click on the three verticle dots at the top right corner. After that, hover over the 'history, and it will open the menu. In the menu, click on the 'history.

    Delete Cookies Step 1

    Step 2 − Here, click on the 'clear browsing data' tab.

    Delete Cookies Step 2

    Step 3 − Check the cookies and other site data check boxes here. After that, click on the 'clear data' button.

    Delete Cookies Step 3

    However, the steps might differ based on what browser you are using.

    This way, you can use any way among the three to clear your browser's cookie.

  • Cookie Attributes

    Cookie Attributes

    The JavaScript cookie attributes are used to set additional information about a cookie such as path, domain, expiry date, etc. In JavaScript, you can specify the cookie attributes while setting up a new cookie or updating the cookie. For example, you can set the cookie’s expiry date using the ‘expires’ attributes.

    In simple terms, cookie attributes are used to control the behavior of the cookies and how the cookie is used in the browser.

    Here, we have listed all cookie attributes in the table below with its description.

    AttributeDescriptionDefault Value
    Name/ValueIt is used to store the cookies in the browser.
    DomainTo specify the domain for whose cookie is valid.Website of domain. For example, tutorialspoint.com
    PathThe path to the directory or web page that sets the cookie./ (entire domain)
    ExpiresIt is used to specify the date and time when the cookie should expire.Current session
    Max-AgeIt is used to specify the time limit after that cookie should expire.Current session
    SecureIf this field contains the word “secure”, then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.false
    HttpOnlyIt prevents accessing the cookies via JavaScript to make cookies secure.false
    SameSiteIt is used to specify how third-party cookies should be handled.Lax
    PriorityIt defines the priority of the cookies.1000
    Site/ServiceTo get information about the origin site of the cookie.
    SourcePortTo get the port of the source for the cookie.
    StoragePartitionIt defines which storage partition is used to store cookies.
    SizeIt represents the size of the cookies.The size depends on the text length.

    However, above all, attributes are optional.

    Also, you can’t manipulate all attributes of the cookies. The browser sets some attributes.

    Check the Attribute Value in the Browser

    You can set the attributes to the cookie, but you can’t access the attributes. To check whether the attribute is set, you can use the browser console.

    Follow the steps below to check cookies in the browser console.

    Step 1 − Right click in the browser. It will open the menu. You need to select the ‘inspect’ option. It will open the developer tool.

    Cookie Attributes Step 1

    Step 2 − After that, you need to go to the Application/ Storage tab.

    Cookie Attributes Step 2

    Step 3 − In the sidebar, select ‘cookies.

    Cookie Attributes Step 3

    Step 4 − Now, click on any cookies to check their name, value, and other attribute values.

    Cookie Attributes Step 4

    The above steps are only for the Chrome web browser. The step can differ according to what browser you are using.

    Here, you will learn each attribute one by one with examples.

    Cookie’s Name/Value Attribute

    The Name attribute is used to store the cookie data. It takes the data as a value. If you want to use the special characters in the value of the ‘Name’ attribute, you need to encode the text using the encodeURIComponent() method.

    Syntax

    Follow the syntax below to set the Name attribute of the cookie.

    let value =encodeURIComponent(cookieValue);
    document.cookie ="name="+ value +";";

    In the above syntax, we have encoded the ‘cookieValue’ using the encodeURIComponent() method and used the encoded value as a name attribute value.

    Example

    In the below code, we set the ‘subscribed’ cookie with a ‘false’ value. You can click the read cookies button to get the cookies.

    <html><body><p id ="output"></p><button onclick ="setCookies()"> Set Cookie </button><br><br><button onclick ="readCookies()"> Read Cookies </button><script>let output = document.getElementById("output");functionsetCookies(){
    			document.cookie ="subscribed=false";// name-value pair
    			output.innerHTML ="Cookie setting successful!";}functionreadCookies(){const allCookies = document.cookie.split("; ");
    			output.innerHTML ="The subscribed cookie is - <br>";for(const cookie of allCookies){const[name, value]= cookie.split("=");if(name =="subscribed"){
    
    				output.innerHTML +=${name} : ${decodeURIComponent(value)} &amp;lt;br&amp;gt;;}}}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Cookie's Path Attribute

    The Path attribute is used to set the scope of the cookie. It defines where cookies should be accessible on the website. You may set the relative or absolute path as a Path attribute value.

    If you set the relative path, all the cookies can be accessible everywhere in the particular or sub-directory.

    Syntax

    Follow the syntax below to set the Path attribute in the cookie.

    document.cookie ="name=value;path=pathStr";

    In the above syntax, you need to replace the 'pathStr' with the actual path string.

    Example

    In the below code, we set the path for the cookie. Here, we set the / (home route). So, cookies can be accessible on each webpage of the website. You may try to get the cookie on the different web pages of the website.

    <html><body><button onclick ="setCookies()"> Set Cookie </button><p id ="output"></p><button onclick ="readCookies()"> Read Cookies </button><script>let output = document.getElementById("output");functionsetCookies(){
    			document.cookie ="signIn=true; path=/";
    			output.innerHTML ="Cookie set successful!";}functionreadCookies(){const allCookies = document.cookie.split("; ");
    			output.innerHTML ="The cookie is : <br>";for(const cookie of allCookies){const[key, value]= cookie.split("=");if(key =="signIn"){
    
    				output.innerHTML +=${key} : ${decodeURIComponent(value)} &amp;lt;br&amp;gt;;}}}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Cookie Expires Attribute

    The 'expires' attribute is used to set the expiry date for the cookie. It takes the date string as a value.

    If you set 0 or past date as a value of the 'expires, the browser will automatically delete the cookie.

    Syntax

    Follow the syntax below to set the expires attribute in the cookie.

    document.cookie ="name=value;expires=dateStr";

    In the above syntax, you need to replace the 'dateStr' with the date string.

    Example

    In the code below, we set the product cookie. Also, we set the expiry date in 2050.

    You may try to set the past expiry date and try to access the cookie. You won't be able to find the cookie.

    <html><body><p id ="output"></p><button onclick ="setCookies()"> Set Cookie </button><br><br><button onclick ="readCookies()"> Read Cookies </button><script>let output = document.getElementById("output");functionsetCookies(){
    			document.cookie ="product=mobile;expires=12 Jan 2050 12:00:00 UTC";
    			output.innerHTML ="Cookie Set Successful!";}functionreadCookies(){const allCookies = document.cookie.split("; ");
    			output.innerHTML ="The cookie is : <br>";for(const cookie of allCookies){const[key, value]= cookie.split("=");if(key =="product"){
    
    				output.innerHTML +=${key} : ${decodeURIComponent(value)} &amp;lt;br&amp;gt;;}}}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Cookie's maxAge Attribute

    The 'maxAge' attribute is an alternative to the 'expires' attribute. It is used to specify the lifetime of the cookie. It takes the seconds as a value.

    When the lifetime of the cookie is finished, it will automatically get deleted.

    Syntax

    Follow the syntax below to pass the 'maxAge' attribute to the cookie.

    document.cookie ="name=value;max-ge=age;";

    In the above syntax, you need to replace the 'age' with the number of seconds.

    Example

    In the below code, we set the total number of seconds equal to 10 days as a value of the maxAge attribute. You can set the lifetime of 1 second for the cookie and try to access the cookie after 1 second.

    <html><body><button onclick ="setCookies()"> Set Cookie </button><button onclick ="readCookies()"> Read Cookies </button><p id ="output"></p><script>const output = document.getElementById("output");functionsetCookies(){
    			document.cookie ="token=1234wfijdn;max-age=864000";}functionreadCookies(){const allCookies = document.cookie.split("; ");
    			output.innerHTML ="The cookie is : <br>";for(const cookie of allCookies){const[key, value]= cookie.split("=");if(key =="token"){
    
    				output.innerHTML +=${key} : ${decodeURIComponent(value)} &amp;lt;br&amp;gt;;}}}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Cookie Domain Attribute

    The domain attribute is used to specify the domain for which the cookie is valid. The default value of the domain from which you are making a request. You may set the domain attribute to set the subdomains.

    Syntax

    Follow the syntax below to set the value of the domain attribute in the cookie.

    document.cookie ="name=value;domain:domain_name ";

    In the above syntax, replace the 'domain_name' with the actual domain, like example.com.

    Example

    In the below code, we set the 'tutorialspoint.com' domain for the cookie.

    <html><body><p id ="output"></p><button onclick ="setCookies()"> Set Cookie </button><button onclick ="readCookies()"> Read Cookies </button><script>const output = document.getElementById("output");functionsetCookies(){
    			document.cookie ="username=abcd;domain:tutorialspoint.com";}functionreadCookies(){const allCookies = document.cookie.split("; ");
    			output.innerHTML ="The cookie is : <br>";for(const cookie of allCookies){const[key, value]= cookie.split("=");if(key =="username"){
    
    				output.innerHTML +=${key} : ${decodeURIComponent(value)} &amp;lt;br&amp;gt;;}}}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Similarly, you can also update the attribute values. For example, you can extend the expiry time of the cookie.

  • Cookies

    What are Cookies ?

    In JavaScript, cookies are piece of data stored in the user’s web browser. The cookies are stored in the key-value pair inside the browser. We can manipulate the cookies using cookie property of document object. We can set or store a cookie in key-value pair using the cookie property. We can read cookies using document’s cookie property and extract the desired information using destructuring.

    Why are Cookies needed?

    Web Browsers and Servers use HTTP protocol to communicate and HTTP is a stateless protocol. But for a commercial website, it is required to maintain session information among different pages.

    For example, you have logged in to a particular website on a particular web page. How do other webpages of the same website know your state that you have already completed the logged-in process? In this case, cookies are used.

    In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics.

    Sometimes, cookies are also used for caching, increasing the website or application performance.

    How It Works ?

    Your server sends some data to the visitor’s browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor’s hard drive. Now, when the visitor arrives at another page on your site, the browser sends the same cookie to the server for retrieval. Once retrieved, your server knows/remembers what was stored earlier.

    Cookies are a plain text data record of 5 variable-length fields −

    • Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.
    • Domain − The domain name of your site.
    • Path − The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page.
    • Secure − If this field contains the word “secure”, then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.
    • Name=Value − Cookies are set and retrieved in the form of key-value pairs

    Cookies were originally designed for CGI programming. The data contained in a cookie is automatically transmitted between the web browser and the web server, so CGI scripts on the server can read and write cookie values that are stored on the client.

    Setting/ Storing Cookies

    JavaScript can manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookies that apply to the current web page.

    The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this.

    document.cookie ="key1 = value1;key2 = value2;expires = date";

    Here the expires attribute is optional. If you provide this attribute with a valid date or time, then the cookie will expire on a given date or time and thereafter, the cookies’ value will not be accessible.

    The cookie string contains the key-value pairs separated by the semi-colons.

    Note − Cookie values may not include semicolons, commas, or whitespace. For this reason, you may want to use the JavaScript escape() function to encode the value before storing it in the cookie. If you do this, you will also have to use the corresponding unescape() function when you read the cookie value.

    Example

    Try the following. It sets a customer name in an input cookie.

    <html><head><script type ="text/javascript">functionWriteCookie(){if( document.myform.customer.value ==""){alert("Enter some value!");return;}
    
            cookievalue =escape(document.myform.customer.value)+";";
            document.cookie ="name="+ cookievalue;
            document.write("Setting Cookies : "+"name="+ cookievalue );}&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;form name ="myform" action =""&gt;
         Enter name:&lt;input type ="text" name ="customer"/&gt;&lt;input type ="button" value ="Set Cookie" onclick ="WriteCookie();"/&gt;&lt;/form&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    https://www.tutorialspoint.com/javascript/src/write_cookie.htm

    Now your machine has a cookie called name. You can set multiple cookies using multiple key = value pairs separated by comma.

    Reading Cookies

    Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie. So you can use this string whenever you want to access the cookie. The document.cookie string will keep a list of name=value pairs separated by semicolons, where name is the name of a cookie and value is its string value.

    You can use strings' split() function to break a string into key and values as follows −

    Example

    Try the following example to get all the cookies.

    <html><head><script type ="text/javascript">functionReadCookie(){var allcookies = document.cookie;
    
            document.write("All Cookies : "+ allcookies );// Get all the cookies pairs in an array
            cookiearray = allcookies.split(';');// Now take key value pair out of this arrayfor(var i=0; i&lt;cookiearray.length; i++){
               name = cookiearray[i].split('=')[0];
               value = cookiearray[i].split('=')[1];
               document.write("Key is : "+ name +" and Value is : "+ value);}}&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;form name ="myform" action =""&gt;&lt;p&gt; click the following button and see the result:&lt;/p&gt;&lt;input type ="button" value ="Get Cookie" onclick ="ReadCookie()"/&gt;&lt;/form&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Note − Here length is a method of Array class which returns the length of an array. We will discuss Arrays in a separate chapter. By that time, please try to digest it.https://www.tutorialspoint.com/javascript/src/reading_cookies.htm

    Note − There may be some other cookies already set on your machine. The above code will display all the cookies set on your machine.

    Setting Cookies Expiry Date

    You can extend the life of a cookie beyond the current browser session by setting an expiration date and saving the expiry date within the cookie. This can be done by setting the expires attribute to a date and time.

    Example

    Try the following example. It illustrates how to extend the expiry date of a cookie by 1 Month.

    <html><head><script type ="text/javascript">functionWriteCookie(){var now =newDate();
    
            now.setMonth( now.getMonth()+1);
            cookievalue =escape(document.myform.customer.value)+";"
            
            document.cookie ="name="+ cookievalue;
            document.cookie ="expires="+ now.toUTCString()+";"
            document.write("Setting Cookies : "+"name="+ cookievalue );}&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;form name ="myform" action =""&gt;
         Enter name:&lt;input type ="text" name ="customer"/&gt;&lt;input type ="button" value ="Set Cookie" onclick ="WriteCookie()"/&gt;&lt;/form&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    https://www.tutorialspoint.com/javascript/src/setting_cookies.htm

    Deleting a Cookie

    Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return nothing. To do this, you just need to set the expiry date to a time in the past.

    Example

    Try the following example. It illustrates how to delete a cookie by setting its expiry date to one month behind the current date.

    <html><head><script type ="text/javascript">functionWriteCookie(){var now =newDate();
    
            now.setMonth( now.getMonth()-1);
            cookievalue =escape(document.myform.customer.value)+";"
               
            document.cookie ="name="+ cookievalue;
            document.cookie ="expires="+ now.toUTCString()+";"
            document.write("Setting Cookies : "+"name="+ cookievalue );}&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;form name ="myform" action =""&gt;
         Enter name:&lt;input type ="text" name ="customer"/&gt;&lt;input type ="button" value ="Set Cookie" onclick ="WriteCookie()"/&gt;&lt;/form&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    https://www.tutorialspoint.com/javascript/src/deleting_cookies.htm

    Updating Cookies

    To update the particular key-value pair in the cookie, you can assign new key-value pair to the document.cookie property. Here, you need to ensure you are using the same key whose value you want to update.

    Syntax

    Follow the syntax below to update the cookies.

    document.cookie="key1=value1";

    In the above syntax, we are updating the value of the key cookie.

    Example

    In the code below, click the set cookies button to set the cookies. It will set the watch value for the cartItem and 10000 for the price.

    After that, you can click the get cookies button to observe the cookies.

    Next, you can click on the update cookies button to update the cookies. It will change the cartItem value to bag and the price to 5000.

    Now, click the get cookies button again to get the updated cookie value.

    <html><body><p id ="output"></p><button onclick ="setCookies()"> Set Cookie </button><br><br><button onclick ="updateCookies()"> Update Cookie </button><br><br><button onclick ="getCookies()"> Get Cookies </button><script>let output = document.getElementById("output");functionsetCookies(){
      document.cookie ="cartItem=watch";
      document.cookie ="price=10000";}functionupdateCookies(){// Updating cookies
      document.cookie ="cartItem=bag"; 
      document.cookie ="price=5000";}functiongetCookies(){//Spliting the cookie stringconst allCookies = document.cookie.split("; "); 
      output.innerHTML ="The cookie data are : <br>";for(const cookie of allCookies){const[key, value]= cookie.split("=");if(key =="cartItem"|| key =="price"){
    
       output.innerHTML +=${key} : ${decodeURIComponent(value)} &amp;lt;br&amp;gt;;}}}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>
  • setInterval Method

    JavaScript setInterval() Method

    In JavaScript, the setInterval() is a window method that is used to execute a function repeatedly at a specific interval. The setTimeout() Method allows you to execute the function only once after the specified time.

    The window object contains the setInterval() method. However, you can execute the setInterval() Method without taking the window object as a reference.

    Syntax

    Following is the syntax to use the setInterval() method in JavaScript

    setInterval(callback,interval, arg1, arg2,..., argN);

    The first two parameters are required others are optional.

    Parameters

    • Callback − It is a callback function that will be executed after every interval.
    • Interval − It is the number of milliseconds after the callback function should be executed.
    • Arg1, arg2, arg3, , argN − They are multiple arguments to pass to the callback function.

    Return Value

    The setInterval() method returns the numeric id.

    Example

    In the code below, the startTimer() function uses the setInterval() method to call the timer() function after every 1000 milliseconds.

    The timer() function increases the value of the second global variable every time it is called by the setInterval() method and prints the counter.

    You can click the button to start a timer in the output.

    <html><body><button onclick ="startTimer()">Start Timer</button><div id ="output"></div><script>let output = document.getElementById('output');var seconds =0;functionstartTimer(){setInterval(timer,1000);// Calls timer() function after every second}functiontimer(){// Callback function
    
         seconds++;
         output.innerHTML +="Total seconds are: "+ seconds +"&lt;br&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    JavaScript setInterval() Method

    Arrow Function with setInterval() Method

    The below example contains almost the same code as the above example. Here, we have passed the arrow function as a first argument of the setInterval() method rather than passing the function name only. You can click the button to start the timer.

    Example

    <html><body><button onclick ="startTimer()">Start Timer</button><div id ="output"></div><script>let output = document.getElementById('output');var seconds =0;functionstartTimer(){setInterval(()=>{
    
            seconds++;
            output.innerHTML +="Total seconds are: "+ seconds +"&lt;br&gt;";},1000);// Calls timer() function after every second}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Arrow Function with setInterval() Method

    Passing More than 2 Arguments to setInterval() Method

    In the code below, we have passed 3 arguments to the setInterval() method. The first argument is a callback function to print the date, the second argument is an interval, and the third argument will be passed to the callback function.

    Example

    <html><body><button onclick ="startTimer()">Start Date Timer</button><div id ="output"></div><script>let output = document.getElementById('output');var seconds =0;functionstartTimer(){let message ="The date and time is: ";setInterval(printDate,1000, message);}functionprintDate(message){let date =newDate();
    
         output.innerHTML += message + date +"&lt;br&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Passing More than 2 Arguments to setInterval() Method

    The clearInterval() Method in JavaScript

    The JavaScript clearInterval() method is used to stop the code execution started using the clearItnerval() method.

    It takes the numeric id returned by the setInterval () method as an argument.

    Syntax

    Follow the syntax below to use the clearInterval() method.

    clearInterval(id);

    Here id is an id returned by the setInterval() method.

    Example

    In the code below, we have used the setInterval() method to show the number after incrementing by 10 and after each second.

    When the number becomes 50, we stop the timer using the clearInterval() method.

    <html><body><div id ="output"></div><script>let output = document.getElementById('output');let number =10;let id =setInterval(()=>{if(number ==50){clearInterval(id);
    
            output.innerHTML +="The time is stopped."}
         output.innerHTML +="The number is: "+ number +"&lt;br&gt;";
         number +=10;},1000);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The number is: 10
    The number is: 20
    The number is: 30
    The number is: 40
    The time is stopped.The number is: 50
    

    Real-time Use Case of the setInterval() Method

    In the above examples, we have printed the messages using the setInterval() method. In this section, we will see the real-time use cases of the setInterval() method.

    Here, we have listed some of the real-time use cases.

    • To refresh the date
    • For slideshow
    • For animation
    • To show the clock on the webpage
    • To update live cricket score
    • To update weather information
    • To run cron jobs

    Here are the real-time examples of the setInterval() method.

    Flipping the color of the HTML element after each interval

    In the code below, we flip the color of the <div> element after every second.

    We have defined the div element in the HTML body.

    In the <head> section, we have added the red and green classes. Also, we added the background color in the red and green classes.

    In JavaScript, we have passed the callback function as the first argument of the setInterval() method, which will be called after every 1000 milliseconds.

    We access the <div> element in the callback function using its id. After that, we check whether the classList of the <div> element contains the red class. If yes, we remove it and add the green class. Similarly, if classList contains the green class, we remove it and add the red class.

    This is how we are flipping the color of the <div> element using the setInterval() method.

    Example

    <html><head><style>.red {background-color: red;}.green {background-color: green;}
    
      #square {height:200px; width:200px;}&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div&gt;Using setInterval() method to flip the color of the HTML element after each interval&lt;/div&gt;&lt;div id ="square"class="red"&gt;&lt;/div&gt;&lt;script&gt;let output = document.getElementById('output');setInterval(function(){let square = document.getElementById('square');if(square.classList.contains('red')){
            square.classList.remove('red');
            square.classList.add('green');}else{
            square.classList.remove('green');
            square.classList.add('red');}},1000);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Flipping color of HTML element after each interval

    Moving Animation Using the setInterval() Method

    In the code below, we create moving animation using the setInterval() method.

    We have created the two nested div elements. The outer div has the parent id, and the inner div has the child id. We have set dimensions for both div elements and position to relative.

    In JavaScript, we have initialized the left variable with 0. After that, we invoke the callback function of the setInterval() method after every 50 milliseconds.

    In each interval, we change the position of the <div> element by 5px, and when the left position becomes 450px, we stop the animation.

    Example

    <html><head><style>
    
      #parent {
         position: relative; 
         height:50px;
         width:500px;
         background-color: yellow;}
      #child {
         position: relative; 
         height:50px;
         width:50px;
         background-color: red;}&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div id ="parent"&gt;&lt;div id ="child"&gt;&lt;/div&gt;&lt;/div&gt;&lt;script&gt;let child = document.getElementById('child');let left =0;// Moving animation using the setInterval() methodsetInterval(()=&gt;{if(left &lt;450){
            left +=5;
            child.style.left = left +'px';}},50);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Moving Animation Using setInterval() Method

    You can also use the setInterval() method to run the particular code asynchronously.

  • setTimeout Method

    JavaScript setTimeout() Method

    In JavaScript, the setTimeout() is a global method that allows you to execute the function or a particular JavaScript code only once after a specified time.

    The window object contains the setTimeout() method. You may use the window object to execute the setTimeout() method.

    The setTimeout() method can also be used to manipulate the DOM elements after the specified time of the user interaction.

    Syntax

    The syntax of the setTimeout() method in JavaScript is as follows −

    window.setTimeout(callback, delay, param1, param2,..., paramN);ORsetTimeout(callback, delay, param1, param2,..., paramN);

    The setTimeout() method takes at least 2 parameters.

    Parameters

    • Callback − It is a callback function that will be called after a specific time. You can pass the arrow function, function expression, or regular expression as a value of this parameter.
    • delay − It is the number of milliseconds after that the callback function should be called. Here, 1 second is equal to 1000 milliseconds.
    • param1, param2, …, paramN − They are optional parameters to be passed as a callback function parameter.

    Return Value

    It returns the numeric id, which you can use to clear timeout.

    Example

    In the below code, we have defined the timeout() function, printing the message in the web page.

    We passed the timeout() function as the first argument of the setTimeout() method, and 1000 milliseconds as a second argument.

    The setTimeout() method will invoke the timeout() function after 1 second or 1000 milliseconds.

    <html><body><div id ="output"></div><script>
    
      document.getElementById('output').innerHTML ="Wait for a message! &lt;br&gt;";setTimeout(timeout,1000);functiontimeout(){
         document.getElementById('output').innerHTML +="This message is printed after 1 second!";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Wait for a message!
    This message is printed after 1 second!
    

    Arrow Function with setTimeout() Method

    In the below code, we have passed the arrow function as the first argument of the setTimeout() method. It works the same as passing the function name as an argument and defining the function outside.

    It prints the message after 2000 milliseconds.

    Example

    <html><body><div id ="output"></div><script>
    
      document.getElementById('output').innerHTML +="You will see the message after 2000 milliseconds! &lt;br&gt;";setTimeout(()=&gt;{
         document.getElementById('output').innerHTML +='Hi! How are you?';},2000);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    You will see the message after 2000 milliseconds!
    Hi! How are you?
    

    Passing More than 2 Arguments to setTimeout() Method

    You can pass more than 2 arguments to the setTimeout() method. The first argument is a callback function, the second argument is a delay in the milliseconds, and other arguments to pass to the function parameter.

    In the code below, we have passed 5 arguments to the setTimeout() method. In the sum() function, we received the last 3 arguments of the seetTimeOut() method as a parameter and summed them.

    Example

    <html><body><div>Wait for a sum of3 number.!</div><div id ="output"></div><script>setTimeout(sum,1000,10,20,30);functionsum(num1, num2, num3){let result = num1 + num2 + num3;
    
         document.getElementById('output').innerHTML ="Sum = "+ result;}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Wait for a sum of 3 number.!
    Sum = 60
    

    Execute Code After Every N Seconds

    We created the counter using the setTimeout() method in the code below.

    We have defined the global variable p for the counter. In the counter() function, we print the counter value and use the setTimeout() method to call the counter function again after 1000 milliseconds.

    Example

    <html><body><div id ="output"></div><script>let output = document.getElementById('output');
    
      output.innerHTML +="The output of the counter is given below. &lt;br&gt;";var p =0;functioncounter(){
         output.innerHTML +="count is - "+ p +".&lt;br&gt;";setTimeout(counter,1000);
         p++;}counter();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The output of the counter is given below.
    count is - 0.
    count is - 1.
    count is - 2.
    count is - 3.
    count is - 4.
    count is - 5.
    count is - 6.
    

    JavaScript clearTimeout() Method

    Sometimes, developers are required to cancel the time out before it executes the function or the JavaScript code. In such cases, you can use the clearTimeout() method.

    Syntax

    You can follow the syntax below to use the clearTimeout() method.

    clearTimeout(id);

    Parameters

    id − It is an id returned by the setTimeout() method to cancel it.

    Example

    In the below code, we have defined the startTimeOut() and stopTimeOut() functions, which will be called when users press the respective buttons.

    In the startTimeOut() function, we set the timeout of the 3 seconds and store the id returned by the setTimeout() method into the timeOut variable.

    In the stopTimeOut() function, we use the clearTimeout() method and pass the timeOut as an argument to clear the timeout.

    <html><body><p>Click the Stop timeout button within 3 seconds after pressing the Start timeout button.</p><button onclick ="startTimeOut()">Start Timeout</button><button onclick ="stopTimeOut()">Stop Timeout</button><p id ="output"></p><script>let output = document.getElementById('output');let timeout;functionstartTimeOut(){
    
         timeout =setTimeout(()=&gt;{
            output.innerHTML ="Timeout is done";},3000);}functionstopTimeOut(){clearTimeout(timeout);
         output.innerHTML ="Timeout is stopped";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    JavaScript clearTimeout() Method

    Zero Delay SetTimeout

    The zero delay timeout means you call the setTimeout() method by passing the 0 milliseconds as an argument.

    As you pass the 0 milliseconds as an argument, it may or may not call the JavaScript code written into the callback function after 0 milliseconds. It totally depends on the pending tasks in the queue. Once the queue of tasks is completed, it will execute the code of the callback function.

    Now, the question is, what is the need of the zero delay timeout?

    Sometimes, you need to execute the particular JavaScript code as soon as possible once the script gets loaded into the browser. In such cases, you can use the setTimeout() method by passing 0 milliseconds as a second argument.

    Syntax

    Follow the syntax below to use the zero-delay timeout.

    setTimeout(callback,0);

    In the above syntax, we have passed the callback function as the first parameter and 0 milliseconds as the second parameter.

    Example

    In the code below, we add a start message, zero delay timeout message, and end message to the web page.

    In the output, you can see that it prints the start message. After that, it prints the end message and the zero delay timeout message. So, it executes the zero delay timeout code when the whole script gets loaded in the browser.

    <html><body><div id ="output"></div><script>let output = document.getElementById('output');
    
      output.innerHTML +="The code execution started. &lt;br&gt;";setTimeout(function(){
         output.innerHTML +="Inside the zero delay timeout. &lt;br&gt;";},0);
      output.innerHTML +="The code execution ended. &lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The code execution started.
    The code execution ended.
    Inside the zero delay timeout.
    

    You can also recursively use the setTimeout() method, as shown in the example of the counter. Furthermore, you can also pass the anonymous function expression as a first parameter, like the arrow function. If you want to execute the particular JavaScript code, you can use the zero delay timeout once the whole script gets executed.

  • Timing Events

    What are the Timing Events?

    JavaScript timing events are used to execute the code after a specified time only once or multiple times. In JavaScript, you can use the timing events to control when a particular task should be executed.

    The ‘window’ object contains the various methods for timing events, which you can use to schedule the tasks. You can call these methods using the window object or without using it.

    Here is the list of methods that can be used to schedule the tasks.

    MethodDescription
    setTimeout()To execute the code after N number of milliseconds only once.
    clearTimeout()To clear the timeout, which was set using the setTimeOut() method.
    setInterval()To execute the particular task after each N milliseconds.
    clearInterval()To clear the interval, which was set using the setInterval() method.

    Let’s understand the timing events via the example below.

    The setTimeout() Method

    <html>
    <body>
       <div id = "output">The message will be printed after 2000 milliseconds! <br></div>
       <script>
    
      setTimeout(() =&gt; {
         document.getElementById('output').innerHTML += 'Hello World &lt;br&gt;';
      }, 2000);
    </script> </body> </html>

    Output

    The message will be printed after 2000 milliseconds!
    Hello World
    

    The clearTimeout() Method

    In the below example, we used the setTimeout() method to print the ‘hello world’ after 3000 milliseconds. We used clearTimeout() method to prevent setTimeout() method to execute.

    Example

    <html>
    <body>
       <p>Message will print after 3 seconds.</p>
       <p>Click the button to prevent timeout to execute.</p>
       <p id="demo"></p>
       <button onclick="stop()">Clear Timeout</button>
       <script>
    
      const myTimeout = setTimeout(greet, 3000);
      function greet() {
         document.getElementById("demo").innerHTML = "Hello World!"
      }
      function stop() {
         clearTimeout(myTimeout);
      }
    </script> </body> </html>

    Output

    The clearTimeout() Method

    The setInterval() and clearInterval() Methods

    In the code below, we have used the setInterval() method to show the number after incrementing by 10 and after each second.

    When the number becomes 50, we stop the timer using the clearInterval() method.

    Example

    <html>
    <body>
       <div id = "output"> </div>
       <script>
    
      let output = document.getElementById('output');
      let number = 10;
      let id = setInterval(() =&gt; {
         if (number == 50) {
            clearInterval(id);
            output.innerHTML += "The time is stopped."
         }
         output.innerHTML += "The number is: " + number + "&lt;br&gt;";
         number += 10;
      }, 1000);
    </script> </body> </html>

    Output

    The number is: 10
    The number is: 20
    The number is: 30
    The number is: 40
    The time is stopped.The number is: 50
    

    Real-time Use Cases of Timing Events

    Here, you will learn the real-time use cases of the timing events.

    • For animation and transition
    • For slideshow and carousel
    • For countdown timers
    • For user authentication timeouts
    • To autosave drafts like Google docs
    • To schedule notifications, email, message, etc.
    • To terminate the session as like banking websites
    • For progress bar

    However, there are other use cases also. You can use the setTimeOut() or setInterval() methods to achieve the above functionalities.

    Whats Next?

    In the following chapters, you will learn setTimeOut() and setInterval() methods in detail.

  • Promises Chaining

    The promise chaining in JavaScript can handle multiple related asynchronous operations even with a single promise. While a single promise handles a single asynchronous operation, the promise chaining allows you to create a sequence of promises. Here success or rejection of one promise triggers the execution of the next promise. This enables you to handle multiple asynchronous operations.

    In JavaScript, we can produce the promise code using the Promise() constructor and consume using the then() method. It handles the single asynchronous operation. To handle the multiple asynchronous operations, we require to use the multiple promises, as shown in the example below.

    Example

    In the code below, we have defined promise1, which gets resolved in 1 second. Also, we have defined the global data variable.

    After that, we used the then() method to consume the promise1, and inside the callback function, we stored the return value from the promise in the data.

    Next, we have defined the promise2, which gets resolved after 2 seconds. Next, we used the then() method with promise2 and used the data variable inside the callback function.

    <html><body><div id ="output"></div><script>let output = document.getElementById("output");var data;// First promiselet promise1 =newPromise((resolve, reject)=>{setTimeout(()=>{resolve(10);},1000);});
    
      promise1.then((value)=&gt;{
         data = value;// Stroing value into the data
         output.innerHTML +="The promise1 is resolved and data is: "+ data +"&lt;br&gt;";});// Second promiselet promise2 =newPromise((resolve, reject)=&gt;{setTimeout(()=&gt;{resolve(20);},2000);});
      promise2.then((value)=&gt;{
         data = data * value;// Using the data from the first promise
         output.innerHTML +="The promise2 is resolved and data is: "+ value +"&lt;br&gt;";
         output.innerHTML +="The final value of the data is: "+ data +"&lt;br&gt;";});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The promise1 is resolved and data is: 10
    The promise2 is resolved and data is: 20
    The final value of the data is: 200
    

    In the above example, we have created two different promises to perform multiple operations on the data returned from the promise1.

    It increases the code complexity and decreases the readability.

    Here, promise chaining comes into the picture.

    JavaScript Promise Chaining

    The concept of promise chaining in JavaScript allows you to do multiple related asynchronous operations with a single promise.

    You can use the multiple then() methods while consuming the promise to perform the multiple asynchronous operations.

    Syntax

    The syntax of the promise chaining in JavaScript is as follows −

    Promise
       .then(callback);.then(callback);....then(callback);

    In the above syntax, we have used multiple then() methods to handle the multiple asynchronous operations. Each then() method executes the single callback function.

    Example

    In the code below, we have defined the promise1. After that, we used the promise chain to perform the multiple asynchronous operations.

    From the first then() method, we return the value after multiplying with 2. In the next then() method, we print the updated value and return the new value after multiplying the old value with 2. Similarly, the operation we are doing is in the third then() method.

    <html><body><div id ="output"></div><script>let output = document.getElementById("output");const promise1 =newPromise((resolve, reject)=>{resolve(2);});// Promise chaining
    
      promise1
      .then((value)=&gt;{
         output.innerHTML ="The square of 2 is "+ value *2+"&lt;br&gt;";return value *2;// Returning a promise for next then() method}).then((value)=&gt;{
         output.innerHTML +="The square of 4 is "+ value *2+"&lt;br&gt;";return value *2;}).then((value)=&gt;{
         output.innerHTML +="The square of 8 is "+ value *2+"&lt;br&gt;";});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The square of 2 is 4
    The square of 4 is 8
    The square of 8 is 16
    

    Multiple Promise Handlers

    You can also use the multiple promise handlers to consume the single promise. However, if you use multiple promise handlers, it is not called promise chaining.

    Example

    In the code below, we have created the promise1.

    After that, we used the multiple promise handlers to consume the promise. Each promise handler solves the promise separately.

    <html><body><div id ="output"></div><script>let output = document.getElementById("output");const promise1 =newPromise((resolve, reject)=>{resolve(2);});
    
    
      promise1
      .then((value)=&gt;{
         output.innerHTML +="Inside the first promise handler. &lt;br&gt;";return value *2;})
      promise1
      .then((value)=&gt;{
         output.innerHTML +="Inside the second promise handler. &lt;br&gt;";return value *2;})
      promise1
      .then((value)=&gt;{
         output.innerHTML +="Inside the third promise handler. &lt;br&gt;";return value *2;})&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Inside the first promise handler.
    Inside the second promise handler.
    Inside the third promise handler.
    

    Error Handling with Promise Chaining

    You can use the catch() method with promise chaining to handle the error.

    If you use the catch() method at last after all then() methods, it catches the error in any then() method and handles it. If you use the catch() method in between then() methods, it catches the error in the then() methods used before it.

    Lets understand it via the example below.

    Example

    In the code below, we have defined the promise and rejected it.

    After that, we used the promise chaining to consume the promise. We used two then() methods and 1 catch() after all then() methods.

    In the output, you can see that as we rejected the promise, control goes into the catch() method.

    <html><body><div id ="output"></div><script>let output = document.getElementById("output");const promise1 =newPromise((resolve, reject)=>{reject("There is an error.");});
    
    
      promise1
      .then((value)=&gt;{
         output.innerHTML +="The returned value is: "+ value +"&lt;br /&gt;";return value +" Everything is fine!";}).then((value)=&gt;{
         output.innerHTML += value;}).catch((error)=&gt;{
         output.innerHTML += error;});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    There is an error.
    

    Returning the Promise

    When you return the value from the then() method, it returns the promise by default and resolves it with a returned value, as it is an asynchronous method.

    However, you can manually return the promise to reject the promise or perform any other operation.

    Example

    In the code below, we have defined the primise1 and used the setTimeOut() method inside the callback function.

    After that, we consume the promise using multiple then() methods. From each then() method, we return a new promise.

    When you return only the value from the then() method, it returns the promise, which gets resolved immediately. But when you want to add some delay, you can return the promise from then() method.

    <html><body><div id ="output"></div><script>let output = document.getElementById("output");const promise1 =newPromise((resolve, reject)=>{setTimeout(()=>{resolve("Stage 1");},500);});
    
    
      promise1
      .then((value)=&gt;{
         output.innerHTML += value +"&lt;br /&gt;";returnnewPromise((resolve, reject)=&gt;{setTimeout(()=&gt;{resolve("Stage 2");},1000);});}).then((value)=&gt;{
         output.innerHTML += value +"&lt;br /&gt;";returnnewPromise((resolve, reject)=&gt;{setTimeout(()=&gt;{resolve("Stage 3");},200);});}).then((value)=&gt;{
         output.innerHTML += value +"&lt;br /&gt;";
         output.innerHTML +="Finished";})&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Stage 1
    Stage 2
    Stage 3
    Finished
    

    Converting Nested Callback Functions into the Promise Chaining

    You learned about the nested callback functions in the JavaScript-callbacks' chapter. It is also called the callback hell due to its complex syntax.

    Here, we will learn to convert the callback hell into the promise chaining to make it more readable.

    Lets look at the example of the nested callback functions.

    Nested Callback functions

    Example

    In the code below, the updateData() function takes the data as a first parameter and the callback function as a second parameter.

    The updateData() function calls the callback function by passing the data as an argument after 1000 milliseconds.

    Next, we have invoked the updateData() function and passed the 10 as a first argument and the anonymous function as a callback function.

    The callback function stores the resultant value into p after adding 1 to the num1 value.

    Next, we call the updateData() function inside the callback function. Also, we have passed the data and callback function as an argument. This way, we have defined the nested callback functions.

    <html><body><div id ="output"></div><script>let output = document.getElementById("output");
    
      output.innerHTML +="Wait for updating the data...&lt;br&gt;";//    Callback hellfunctionupdateData(data, callback){setTimeout(()=&gt;{callback(data);},1000);}updateData(10,function(num1){let p =1+ num1;updateData(30,function(num2){let q =1+ num2;updateData("The numeric value is: "+(p + q),function(answer){
               output.innerText += answer;});});});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Wait for updating the data...
    The numeric value is: 42
    

    Now, lets learn to convert the above example into promise chaining.

    Converting nested callback functions to promise chaining

    Example

    In the code below, the updateData() function returns a single promise.

    After that, we used the promise chaining, an alternative to the callback hell defined in the above example.

    <html><body><div id ="output"></div><script>let output = document.getElementById("output");
    
      output.innerHTML +="Wait for updating the data...&lt;br&gt;";functionupdateData(data){returnnewPromise((resolve, reject)=&gt;{setTimeout(()=&gt;{resolve(data);},1000);});}updateData(10).then((num1)=&gt;{let p =1+ num1;returnupdateData(p);}).then((num2)=&gt;{let q =31;returnupdateData("The final value is: "+(num2 + q));}).then((res)=&gt;{
         output.innerText += res;});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Wait for updating the data...
    The final value is: 42
    

    Real-time Examples of Promise Chaining

    In real-time development, you can use the promise chaining to fetch the data and perform the operations on the data.

    Example

    In the code below, when users click the fetch data button, it invokes the fetchData() function.

    In the fetchData() function, we have used the fetch() API to fetch data from the API.

    After that, we used the then() method to convert the data into JSON.

    Next, we used the then() method again to print the JSON data.

    <html><body><button onclick ="fetchData()"> Fetch Data </button><div id ="output"></div><script>let output = document.getElementById("output");functionfetchData(){fetch('https://jsonplaceholder.typicode.com/todos/1').then(response=> response.json())// Promise chaining.then((data)=>{
    
            output.innerHTML +="The data is - "+JSON.stringify(data);})}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Real-time Examples of Promise Chaining

    Print Page

  • Promisification

    Promisification in JavaScript

    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.

    <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
    
         document.getElementById("output").innerHTML += sum;});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The sum of 5 and 10 is: 15
    

    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.

    <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)=&gt;{
         output.innerHTML = message;}).catch((err)=&gt;{
         output.innerHTML = err;})&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</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

    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.

    JavaScript Event Loop

    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.

    <html><body><div id ="output"></div><script>const output = document.getElementById("output");
    
      output.innerHTML +="The start of the code execution. &lt;br&gt;";// Creating the promiselet promise =newPromise(function(resolve, reject){resolve("The promise is resolved. &lt;br&gt;");});// Consuming the promise code
      promise.then(function(result){
         output.innerHTML += result;});
      output.innerHTML +="The end of the code execution. &lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</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.

    <html><body><div id ="demo"></div><script>let output = document.getElementById("demo");
    
      output.innerHTML +="The start of the code execution.&lt;br&gt;";setTimeout(function(){
         output.innerHTML +="The code execution is being delayed for 0 seconds. &lt;br&gt;";},0);
      output.innerHTML +="The end of the code execution.&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</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.

    <html><body><div id ="output"></div><script>let output = document.getElementById("output");
    
      output.innerHTML +="Start &lt;br&gt;";setTimeout(function(){// Macro task
         output.innerHTML +="In setTimeOut() method. &lt;br&gt;";},0);let promise =newPromise(function(resolve, reject){resolve("In Promise constructor. &lt;br&gt;");});
      promise.then(function(value){// Micro tasks
         output.innerHTML += value;});
      output.innerHTML +="End &lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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.