Blog

  • Storage API

    What is Web Storage API?

    The web storage API in JavaScript allows us to store the data in the user’s local system or hard disk. Before the storage API was introduced in JavaScript, cookies were used to store the data in the user’s browser.

    The main problem with the cookies is that whenever browsers request the data, the server must send it and store it in the browser. Sometimes, it can also happen that attackers can attack and steal the data.

    In the case of the storage API, we can store the user’s data in the browsers, which remains limited to the user’s device.

    JavaScript contains two different objects to store the data in the local.

    • localStorage
    • sessionStorage

    Here, we have explained the local and session storage.

    The Window localStorage Object

    The localStorage object allows you to store the data locally in the key-value pair format in the user’s browser.

    You can store a maximum of 5 MB data in the local storage.

    Whatever data you store into the local storage, it never expires. However, you can use the removeItem() method to remove the particular or clear() to remove all items from the local storage.

    Syntax

    We can follow the syntax below to set and get items from the browser’s local storage.

    localStorage.setItem(key, value);// To set key-value pair
    localStorage.getItem(key);// To get data using a key

    In the above syntax, the setItem() method sets the item in the local storage, and the getItem() method is used to get the item from the local storage using its key.

    Parameters

    • key − It can be any string.
    • value − It is a value in the string format.

    Example

    In the below code, we set the ‘fruit’ as a key and ‘Apple’ as a value in the local storage inside the setItem() function. We invoke the setItem() function when users click the button.

    In the getItem() function, we get the value of the ‘fruit’ key from the local storage.

    Users can click the set item button first and then get the item to get the key-value pair from the local storage.

    <html><body><button onclick ="setItem()"> Set Item </button><button onclick ="getItem()"> Get Item </button><p id ="demo"></p><script>const output = document.getElementById('demo');functionsetItem(){
    
         localStorage.setItem("fruit","Apple");}functiongetItem(){const fruitName = localStorage.getItem("fruit");
         output.innerHTML ="The name of the fruit is: "+ fruitName;}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    The localStorage doesn't allow you to store the objects, functions, etc. So, you can use the JSON.stringify() method to convert the object into a string and store it in the local storage.

    Example: Storing the object in the local storage

    In the below code, we have created the animal object. After that, we used the JSON.stringify() method to convert it into the string and store it as a value of the 'animal' object.

    Users can click the set item button to set the object into the local storage and get the item button to get the key-value pair from the local storage.

    <html><body><button onclick ="setItem()"> Set Item </button><button onclick ="getItem()"> Get Item </button><p id ="demo"></p><script>const output = document.getElementById('demo');functionsetItem(){const animal ={
    
            name:"Lion",
            color:"Yellow",
            food:"Non-vegetarian",}
         localStorage.setItem("animal",JSON.stringify(animal));}functiongetItem(){const animal = localStorage.getItem("animal");
         output.innerHTML ="The animal object is: "+ animal;}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example: Removing the items from the local storage

    In the below code, we set the 'name' and 'john' key-value pair in the local storage when the web page loads into the browser.

    After that, users can click the get item button to get the item from local storage. It will show you the name.

    You can click the get item button again after clicking the remove item button, and it will show you null as the item got deleted from the local storage.

    <html><body><button onclick ="getItem()"> Get Item </button><button onclick ="removeItem()"> Remvoe Item </button><p id ="demo"></p><script>const output = document.getElementById('demo');
    
      localStorage.setItem('name','John');functiongetItem(){
         output.innerHTML ="The name of the person is: "+ 
    localStorage.getItem('name');}functionremoveItem(){
         localStorage.removeItem('name');
         output.innerHTML ='Name removed from local storage. Now, you can\'t get it.';}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    The Window sessionStorage Object

    The sessionStorage object also allows storing the data in the browser in the key-value pair format.

    It also allows you to store the data up to 5 MB.

    The data stored in the session storage expires when you close the tab of the browsers. This is the main difference between the session storage and local storage. You can also use the removeItem() or clear() method to remove the items from the session storage without closing the browser's tab.

    Note Some browsers like Chrome and Firefox maintain the session storage data if you re-open the browser's tab after closing it. If you close the browser window, it will definitely delete the session storage data.

    Syntax

    Follow the syntax below to use the session storage object to set and get data from the session storage.

    sessionStorage.setItem(key, value);// To set key-value pair
    sessionStorage.getItem(key);// To get data using a key

    The setItem() and getItem() methods give the same result with the sessionStorage object as the localStorage object.

    Parameters

    • key − It is a key in the string format.
    • value − It is a value for the key in the string format.

    Example

    In the below code, we used the 'username' as a key and 'tutorialspoint' as a value. We store the key-value pair in the sessionStorage object using the setItem() method.

    You can click the get item button after clicking the set item button to get the key-value pair from the session storage.

    <html><body><button onclick ="setItem()"> Set Item </button><button onclick ="getItem()"> Get Item </button><p id ="output"></p><script>const output = document.getElementById('output');functionsetItem(){
    
         sessionStorage.setItem("username","tutorialspoint");}functiongetItem(){const username = sessionStorage.getItem("username");
         output.innerHTML ="The user name is: "+ username;}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    You can't store the file or image data directly in the local or session storage, but you can read the file data, convert it into the string, and store it in the session storage.

    Example

    In the below code, we have used the <input> element to take the image input from users. When a user uploads the image, it will call the handleImageUpload() function.

    In the handleImageUpload() function, we get the uploaded image. After that, we read the image data using the FileReader and set the data into the session storage.

    In the getImage() function, we get the image from the session storage and set its data as a value of the 'src' attribute of the image.

    Users can upload the image first and click the get Image button to display the image on the web page.

    <html><body><h2> Upload image of size less than 5MB</h2><input type ="file" id ="image" accept ="image/*" onchange ="handleImageUpload()"><div id ="output"></div><br><button onclick ="getImage()"> Get Image </button><script>// To handle image uploadfunctionhandleImageUpload(){const image = document.getElementById('image');const output = document.getElementById('output');const file = image.files[0];// Read Image fileif(file){const reader =newFileReader();
    
            reader.onload=function(event){const data = event.target.result;// Storing the image data in sessionStorage
               sessionStorage.setItem('image', data);};
            reader.readAsDataURL(file);}}// Function to get imagefunctiongetImage(){let data = sessionStorage.getItem("image");
         output.innerHTML =&amp;lt;img src="${data}" alt="Uploaded Image" width="300"&amp;gt;;}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    You can also use the removeItem() or clear() method with the sessionStorage object like the localStorage.

    Cookie Vs localStorage Vs sessionStorage

    Here, we have given the difference between the cookie, localStorage, and sessionStorage objects.

    FeatureCookieLocal storageSession storage
    Storage Limit4 KB per cookie5 MB5 MB
    ExpiryIt has an expiry date.It never expires.It gets deleted when you close the browser window.
    AccessibilityIt can be accessed on both the client and server.It can be accessed by the client only.It can be accessed by the client only.
    SecurityIt can be vulnerable.It is fully secured.It is fully secured.

    Storage Object Properties and Methods

    Property/MethodDescription
    key(n)To get the name of the nth key from the local or session storage.
    lengthTo get the count of key-value pairs in the local or session storage.
    getItem(key)To get a value related to the key passed as an argument.
    setItem(key, value)To set or update key-value pair in the local or session storage.
    removeItem(key)To remove key-value pairs from the storage using its key.
    clear()To remove all key-value pairs from the local or session storage.
  • History API

    Web History API

    In JavaScript, the history API allows us to access the browsers history. It can be used to navigate through the history.

    JavaScript History API provides us with methods to manipulate window history object. History object is a property of JavaScript window object. The window history object contains the array of visited URLs in the current session

    The history API is very powerful tool to create may useful effects. For example, we can use it to implement history based undo redo system.

    How to use JavaScript History API?

    The History API is a very simple API to use. There are just a few methods and a property that you need to know about:

    • back() − This method navigates back to the previous page in the history.
    • forward() − This method navigates forward to the next page in the history.
    • go() − This method navigates to a specific page in the history. The number that you pass to the go() method is the relative position of the page that you want to navigate to. For example, to navigate to the previous page in the history, you would pass -1 to the go() method.
    • length − This property returns the length of the history list. It tells us the number of pages that have been visited by the user.

    Syntax

    Followings are the syntaxes to use the different methods and property of the history object −

    // Load the previous URL in the history list
    history.back();// Load the next URL in the history list
    history.forward();// Load the page through its number
    history.go(-2);// This will go to the previous 2nd page
    history.go(2);// This will go to the next 2nd page// Get the length of the history listconst length = history.length;

    Loading Previous Page in History List

    The JavaScript history back() method of the history object loads the previous URL in the history list. We can also use the history go() method to load the previous page. The difference between these two methods is that back() method only load the immediate previous URL in history list but we can use the go() method to load any previous URL in the history list.

    Example: Using back() method to load previous page

    In the example below, we have used history back() method to load the previous page the user has already visited.

    Please note that if you have no previous page in the history list (i.e., you have not visited any page previously), the back() method will not work.

    We have implemented a back button, on clicking that we can load the previous visited page.

    <html><body><p> Click "Load Previous Page" button to load previous visited page </p><button onclick="goback()"> Load Previous Page </button><p id ="output"></p><script>functiongoback(){
    
            history.back();
            document.getElementById("output").innerHTML +="You will have gone to previous visited page if it exists";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example: Using go() method to load the previous page

    In the example bellow, we have used the history go() method to load to the 2nd previous visited page from the current web page.

    <html><body><p> Click the below button to load 2nd previous visited page</p><button onclick ="moveTo()"> Load 2nd Previous Page </button><p id ="output"></p><script>functionmoveTo(){
    
         history.go(-2);
         document.getElementById("output").innerHTML ="You will have forwarded to 2nd previous visited page if it exists.";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Loading Next Page in History List

    The JavaScript history forward() method of the history object loads the next URL in the history list. We can also use the history go() method to load the next page. The difference between these two methods is that forward() method only loads the immediate next URL in history list but we can use the go() method to load any next URL in the history list.

    Example: Using forward() method to load next page

    In the below code, click the button to go to the next URL. It works as the forward button of the browser.

    <html><body><p> Click "Load Next Page" button to load next visited page</p><button onclick ="goForward()"> Load Next Page </button><p id ="output"></p><script>functiongoForward(){
    
         history.forward();
         document.getElementById("output").innerHTML ="You will have forwarded to next visited page if it exists."}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example: Using go() method to load next page

    In the example below, we have used the go() method to move to the 2nd previous page from the current web page.

    <html><body><p> Click the below button to load  next 2nd visited page</p><button onclick ="moveTo()"> Load 2nd Next Page </button><p id ="output"></p><script>functionmoveTo(){
    
         history.go(2);
         document.getElementById("output").innerHTML ="You will have forwarded to 2nd next visited page if it exists.";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Get the length of the history list

    We can use the history.length proerty to get the length of history list.

    Example

    Try the follwing example −

    <html><body><p> Click the below button to get the lenght of history list</p><button onclick ="moveTo()"> Get Lenght of History List </button><p id ="output"></p><script>const output = document.getElementById("output");functionmoveTo(){
    
         output.innerHTML = history.length;}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>
  • Web API

    A Web API is an application programming interface (API) for web. The concept of the Web API is not limited to JavaScript only. It can be used with any programming language. Lets learn what web API is first.

    What is Web API?

    The API is an acronym for the Application Programming Interface. It is a standard protocol or set of rules to communicate between two software components or systems.

    A web API is an application programming interface for web.

    The API provides an easy syntax to use the complex code. For example, you can use the GeoLocation API to get the coordinates of the users with two lines of code. You dont need to worry about how it works in the backend.

    Another real-time example you can take is of a power system at your home. When you plug the cable into the socket, you get electricity. You dont need to worry about how electricity comes into the socket.

    There are different types of web APIs, some are as follow −

    • Browser API (Client-Side JavaScript API)
    • Server API
    • Third Party APIs

    Lets discuss each of the above type of web APIs in detail −

    Browser API (Client-side JavaScript API)

    The browser APIs are set of Web APIs that are provided by the browsers.

    The browser API is developed on top of the core JavaScript, which you can use to manipulate the web page’s functionality.

    There are multiple browser APIs available which can be used to interact with the web page.

    Following is a list of common browser APIs −

    • Storage API − It allows you to store the data in the browser’s local storage.
    • DOM API − It allows you to access DOM elements and manipulate them.
    • History API − It allows you to get the browsers history.
    • Fetch API − It allows you to fetch data from web servers.
    • Forms API − It allows you to validate the form data.

    Server API

    A server API provides different functionalities to the web server. Server APIs allow developers to interact with server and access data and resources.

    For example, REST API is a server API that allows us to create and consume the resources on the server. A JSON API is popular API for accessing data in JSON format. The XML API is a popular API for accessing data in XML format.

    Third-party APIs

    The third-party API allows you to get the data from their web servers. For example, YouTube API allows you to get the data from YouTubes web server.

    Here is the list of common third-party APIs.

    • YouTube API − It allows you to get YouTube videos and display them on the website.
    • Facebook API − It allows you to get Facebook posts and display them on the website.
    • Telegram API − It allows you to fetch and send messages to the telegram.
    • Twitter API − It allows you to get tweets from Twitter.
    • Pinterest API − It allows you to get Pinterest posts.

    You can also create and expose API endpoints for your own software. So, other applications can use your API endpoints to get the data from your web server.

    Fetch API: An Example of Web API

    Here is an example of how to use the fetch API. In the below example, we Fetch API to access data from a given URL (‘https://jsonplaceholder.typicode.com/todos/5). The fetch() method returns a promise that we handle using the then block. First, we convert the data into the JSON format. After that, we convert the data into the string and print it on the web page.

    <html><body><h3> Fetch API: An Example of Web API</h3><div id ="output"></div><script>constURL='https://jsonplaceholder.typicode.com/todos/5';fetch(URL).then(res=> res.json()).then(data=>{
    
            document.getElementById('output').innerHTML +="The data accessed from the API: "+"&lt;br&gt;"+JSON.stringify(data);});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    JavaScript Web API List

    Here, we have listed the most common web APIs.

    APIDescription
    Console APIIt is used to interact with the browsers console.
    Fetch APIIt is used to fetch data from web servers.
    FullScreen APIIt contains various methods to handle HTML elements in full-screen mode.
    GeoLocation APIIt contains the methods to get the users current location.
    History APIIt is used to navigate in the browser based on the browsers history.
    MediaQueryList APIIt contains methods to query media.
    Storage APIIt is used to access the local and session storage.
    Forms APIIt is used to validate the form data.

    In upcoming chapters, we will cover the above APIs in details/>

  • Console Object

    Window Console Object

    In JavaScript, the ‘console’ object is a property of the window object. It allows the developers to access the debugging console of the browser.

    The console object contains the various methods used for different functionalities. In Node.js, the console object is used to interact with the terminal.

    We access the console object using the window object or without using the window object – window.console or just console.

    Console Object Methods

    There are many methods available on the console object. These methods are used to perform a number of task such testing, debugging and logging.

    You may access the ‘console’ object methods using the following syntax −

    window.console.methodName();OR
    console.methodName();

    You can observe outputs in the console. To open the console, use the Ctrl + shift + I or Cmd + shift + I key.

    Below, we will cover some methods of the console object with examples.

    JavaScript console.log() Method

    You can use the console.log() method to print the message in the debugging console. It takes the expression or text message as an argument.

    Syntax

    Follow the syntax below to use the console.log() method.

    console.log(expression);

    In the above syntax, the expression can be a variable, mathematical expression, string, etc., which you need to print in the console.

    Example

    In the below code, clicking the button will invoke the ‘printMessage’ function. The function prints the string text and number value in the console.

    <html><body><h2> JavaScript console.log() Method </h2><button onclick ="printMessage()"> Print Message in Console </button><p> Please open the console before you click "Print Message in Console" button</p><script>functionprintMessage(){
    
         console.log("You have printed message in console!");let num =10;
         console.log(num);}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    JavaScript console.error() Method

    The console.error() method prints the error message in the console, highlighting the error with a red background.

    Syntax

    Follow the syntax below to use the console.error() method.

    console.error(message);

    The console.error() message takes a message as an argument.

    Example

    In the below code, printError() function logs the error in the console when you click the button. You can observe the error highlighted with the red background.

    <html><body><h2> JavaScript console.error() Method </h2><button onclick="printError()"> Print Error Message in Console </button><p> Please open the console before you click " Print Error Message in Console" button.</p><script>functionprintError(){
    
         console.error("Error occured in the code!");}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    JavaScript console.clear() Method

    The console.clear() method clears the console.

    Syntax

    Follow the syntax below to use the console.clear() method.

    console.clear()

    Example

    In the below code, we print messages to the console. After that, when you click the button, it executes the clearConsole() function and clears the console using the console.clear() method.

    <html><body><h2> JavaScript console.clear() Method </h2><button onclick ="clearConsole()"> Clear Console </button><p> Please open the console before you click "Clear Console" button</p><script>
    
      console.log("Hello world!");
      console.log("Click the button to clear the console.");functionclearConsole(){
         console.clear();}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    The console object methods list

    Here, we have listed all methods of the console object.

    MethodMethod Description
    assert()It prints the error message in the console if the assertion passed as a parameter is false.
    clear()It clears the console.
    count()It is used to count how many times the count() method is invoked at a specific location.
    error()It displays the error message in the console.
    group()It is used to create a group of messages in the console.
    groupCollapsed()It is used to create a new collapsed group of messages in the console.
    groupEnd()It is used to end the group.
    info()It shows the informational or important message in the console.
    log()It prints the message into the output.
    table()It shows the data in the tabular format in the console.
    time()It is used to start the time in the console.
    timeEnd()It stops the timer started by the time() method.
    trace()It displays the stack trace in the console.
    warn()It shows the warning message in the console.
  • Location Object

    Window Location Object

    The location object in JavaScript provides information about the browser’s location, i.e., URLs. It is a built-in property of both the window and document objects. We can access it using either window.location or document.location.

    The ‘location’ object contains various properties and methods to get and manipulate the information of the browser’s location (URL).

    JavaScript Location Object Properties

    We can use the properties of the location object to get information of URL:

    • hash − This property is used to set or get the anchor part of the URL.
    • host − This property is used to set or get the hostname or port number of the URL.
    • hostname − This property is used to set the hostname.
    • href − This property is used to set or get the URL of the current window.
    • origin − This property returns the protocol, domain, and port of the URL.
    • pathname − This property updates or gets the path name.
    • port − This property updates or gets the port of the URL.
    • protocol − This property updates or gets the protocol.
    • search − This property is used to set or get the query string of the URL.

    Syntax

    Follow the syntax below to access the location object’s properties and methods −

    window.location.property;

    OR

    location.property;

    You may use the ‘window’ object to access the ‘location’ object.

    Here, we have demonstrated the use of some properties of the location object with examples.

    Example: Accessing location host property

    The location.host property returns the host from the current URL. However, you can also change the host using it.

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

    Output

    The host of the current location is:

    Example: Accessing location protocol property

    The location.protocol propery is used to get used in the current URL. You can also use it to update the protocol.

    Try the following example to use the location.protocol property -

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

    Output

    The protocol of the current location is: https:
    

    Example: Accessing location hostname property

    The location.hostname property returns the host name of the current URL. You can use it to the hostname as well.

    Try the following example to use location.hostname property

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

    Output

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

    Example: Accessing location pathname property

    The location.pathname property returns the path name of the current location. You can set the path name using it.

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

    Output

    The protocol of the current location is: /javascript/javascript_location_object.htm
    

    JavaScript Location Object Methods

    We can also use the methods of the location object to navigation to new URLs −

    • assign(url) − This method loads a new document at the specified URL.
    • replace(url) − This method replaces the current document with a new document at the specified URL.
    • reload() − This method reloads the current document.

    JavaScript location assign() method

    The location.assign() method takes the URL and changes the URL in the current window. In short, it opens a new web page.

    Syntax

    Follow the syntax below to use the location.assign() method in JavaScript −

    location.assign();

    Example

    In the below code, when you click the 'Go to home page' button, it will redirect you to the home page of the tutorialpoint website.

    <html><body><div id="output"></div><button onclick="changePage()">Go to Home Page</button><script>let output = document.getElementById("output");functionchangePage(){
    
         window.location.assign("https://www.tutorialspoint.com/");}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Location Object Properties List

    Here, we have listed all properties of the Location object.

    PropertyDescription
    hashIt is used to set or get the anchor part of the URL.
    hostIt is used to set or get the hostname or port number of the URL.
    hostnameIt is used to set the hostname.
    hrefIt is used to set or get the URL of the current window.
    originIt returns the protocol, domain, and port of the URL.
    pathnameTo update or get the path name.
    portTo update or get the port of the URL.
    protocolTo update or get the protocol.
    searchTo set or get the query string of the URL.

    Location Object Methods List

    Here, we have listed all methods of the Location object.

    MethodDescription
    assign()To load resources at a particular URL.
    reload()To reload the web page.
    replace()To replace the resources of the current webpage with another webpage's resources.
    toString()Returns the URL in the string format.

  • Navigator Object

    Window Navigator Object

    The navigator object in JavaScript is used to access the information of the user’s browser. Using the ‘navigator’ object, you can get the browser version and name and check whether the cookie is enabled in the browser.

    The ‘navigator’ object is a property of the window object. The navigator object can be accessed using the read-only window.navigator property.

    Navigator Object Properties

    There are many properties of navigator object that can be used to access the information about the user’s browser.

    Syntax

    Follow the syntax below to use to access a property of navigator object in JavaScript.

    window.navigator.proeprty;OR
    navigator.property;

    You may use the ‘window’ object to access the ‘navigator’ object.

    Here, we have listed all properties of the Navigator object.

    PropertyDescription
    appNameIt gives you a browser name.
    appVersionIt gives you the browser version.
    appCodeNameIt gives you the browser code name.
    cookieEnabledIt returns a boolean value based on whether the cookie is enabled.
    languageIt returns the browser language. It is supported by Firefox and Netscape only.
    pluginsIt returns the browser plugins. It is supported by Firefox and Netscape only.
    mimeTypes[]It gives you an array of Mime types. It is supported by Firefox and Netscape only.
    platformIt gives you a platform or operating system in which the browser is used.
    onlineReturns a boolean value based on whether the browser is online.
    productIt gives you a browser engine.
    userAgentIt gives you a user-agent header of the browser.

    Example: Accessing Navigator Object Properties

    We used the different properties in the below code to get the browser information.

    The appName property returns the browser’s name, appCodeName returns the code name of the browser, appVersion returns the browser’s version, and the cookieEnabled property checks whether the cookies are enabled in the browser.

    <html><body><p> Browser Information</p><p id ="demo"></p><script>
    
      document.getElementById("demo").innerHTML ="App Name: "+ navigator.appName +"&lt;br&gt;"+"App Code Name: "+ navigator.appCodeName +"&lt;br&gt;"+"App Version: "+ navigator.appVersion +"&lt;br&gt;"+"Cookie Enabled: "+ navigator.cookieEnabled +"&lt;br&gt;"+"Language: "+ navigator.language +"&lt;br&gt;"+"Plugins: "+ navigator.plugins +"&lt;br&gt;"+"mimeTypes[]: "+ navigator.mimeTypes +"&lt;br&gt;"+"platform: "+ navigator.platform +"&lt;br&gt;"+"online: "+ navigator.online +"&lt;br&gt;"+"product: "+ navigator.product +"&lt;br&gt;"+"userAgent: "+ navigator.userAgent;&lt;/script&gt;&lt;p&gt;Please note you may get different result depending on your browser.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Browser Information
    
    App Name: Netscape
    App Code Name: Mozilla
    App Version: 5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36
    Cookie Enabled: true
    Language: en-US
    Plugins: [object PluginArray]
    mimeTypes[]: [object MimeTypeArray]
    platform: Win32
    online: undefined
    product: Gecko
    userAgent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36
    
    Please note you may get different result depending on your browser.
    

    Example

    In the example below, we accessed the navigator object as a property of the window object. Then we accessed different properties of this navigator object.

    <html><body><p> Browser Information</p><p id ="demo"></p><script>
    	  document.getElementById("demo").innerHTML ="App Name: "+ window.navigator.appName +"<br>"+"App Code Name: "+ window.navigator.appCodeName +"<br>"+"App Version: "+ window.navigator.appVersion +"<br>"+"Cookie Enabled: "+ window.navigator.cookieEnabled +"<br>"+"Language: "+ window.navigator.language +"<br>"+"Plugins: "+ window.navigator.plugins +"<br>"+"mimeTypes[]: "+ window.navigator.mimeTypes +"<br>"+"platform: "+ window.navigator.platform +"<br>"+"online: "+ window.navigator.online +"<br>"+"product: "+ window.navigator.product +"<br>"+"userAgent: "+ window.navigator.userAgent;</script><p>Please note you may get different result depending on your browser.</p></body></html>

    Output

    Browser Information
    
    App Name: Netscape
    App Code Name: Mozilla
    App Version: 5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36
    Cookie Enabled: true
    Language: en-US
    Plugins: [object PluginArray]
    mimeTypes[]: [object MimeTypeArray]
    platform: Win32
    online: undefined
    product: Gecko
    userAgent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36
    
    Please note you may get different result depending on your browser.
    

    JavaScript Navigator Object Methods

    The Navigator object contains only one method.

    MethodDescription
    javaEnabled()It checks whether the Java is enabled in the web browser.

    Example: Navigator javaEnabled() Method

    In the below code, we used the javaEnabled() method of the navigator object to check whether the java is enabled in the browser.

    <html><body><p id ="output"></p><script>const output = document.getElementById("output");if(navigator.javaEnabled()){
    
         output.innerHTML +="Java is enabled in the browser!";}else{
         output.innerHTML +="Please, enable the Java!";}&lt;/script&gt;&lt;p&gt;Please note you may get different result depending on your browser.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Please, enable the Java!
    
    Please note you may get different result depending on your browser.

  • History Object

    Window History Object

    In JavaScript, the window ‘history’ object contains information about the browser’s session history. It contains the array of visited URLs in the current session.

    The ‘history’ object is a property of the ‘window’ object. The history property can be accessed with or without referencing its owner object, i.e., window object.

    Using the ‘history’ object’s method, you can go to the browser’s session’s previous, following, or particular URL.

    History Object Methods

    The window history object provides useful methods that allow us to navigate back and forth in the history list.

    Follow the syntax below to use the ‘history’ object in JavaScript.

    window.history.methodName();OR
    history.methodName();

    You may use the ‘window’ object to access the ‘history’ object.

    JavaScript History back() Method

    The JavaScript back() method of the history object loads the previous URL in the history list.

    Syntax

    Follow the syntax below to use the history back() method.

    history.back();

    Example

    In the below code’s output, you can click the ‘go back’ button to go to the previous URL. It works as a back button of the browser.

    <html><body><p> Click "Go Back" button to load previous URL</p><button onclick="goback()"> Go Back </button><p id ="output"></p><script>functiongoback(){
    
         history.back();
         document.getElementById("output").innerHTML +="You will have gone to previous URL if it exists";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    JavaScript History forward() Method

    The forward() method of the history object takes you to the next URL.

    Syntax

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

    history.forward();

    Example

    In the below code, click the button to go to the next URL. It works as the forward button of the browser.

    <html><body><p> Click "Go Forward" button to load next URL</p><button onclick ="goforward()"> Go Forward </button><p id ="output"></p><script>functiongoforward(){
    
         history.forward();
         document.getElementById("output").innerHTML ="You will have forwarded to next URL if it exists."}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    JavaScript History go() Method

    The go() method of the history object takes you to the specific URL of the browser's session.

    Syntax

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

    history.go(count);

    In the above syntax, 'count' is a numeric value representing which page you want to visit.

    Example

    In the below code, we use the go() method to move to the 2nd previous page from the current web page.

    <html><body><p> Click the below button to load 2nd previous URL</p><button onclick ="moveTo()"> Move at 2nd previous URL</button><p id ="output"></p><script>functionmoveTo(){
    
         history.go(-2);
         document.getElementById("output").innerHTML ="You will have forwarded to 2nd previous URL if it exists.";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example

    In the below code, we use the go() method to move to the 2nd previous page from the current web page.

    <html><body><p> Click the below button to load 2nd next URL</p><button onclick ="moveTo()"> Move at 2nd next URL</button><p id ="output"></p><script>functionmoveTo(){
    
         history.go(2);
         document.getElementById("output").innerHTML ="You will have forwarded to 2nd next URL if it exists.";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Following is the complete window history object reference including both properties and methods −

    History Object Property List

    The history object contains only the 'length' property.

    PropertyDescription
    lengthIt returns the object's length, representing the number of URLS present in the object.

    History Object Methods List

    The history object contains the below 3 methods.

    MethodDescription
    back()It takes you to the previous web page.
    forward()It takes you to the next web page.
    go()It can take you to a specific web page.
  • Screen Object

    Window Screen Object

    The screen object in JavaScript is a property of the ‘window’ object. The ‘screen’ object’s properties contain information about the device’s screen. The screen object can be accessed by using the window.screen syntax. We can also access it without using the window object.

    Screen Object Properties

    The screen object has a number of properties that provide information about the screen’s orientation, resolution, and more. These properties can be used to develop applications that are responsive to different screen sizes and orientations.

    Following are some properties of the JavaScript screen object −

    • width − The width of the screen in pixels.
    • height − The height of the screen in pixels.
    • availWidth − The width of the screen, minus the width of the window taskbar.
    • availHeight − The height of the screen, minus the height of the window taskbar.
    • colorDepth − The number of bits per pixel that the screen can display.
    • pixelDepth − The number of bits per pixel that the screen is actually using.

    Screen Object Property Syntax

    Follow the syntax below to use the property of the screen object in JavaScript −

    window.screen.property;OR
    screen.property;

    You may or may not use the ‘window’ object to access the screen object.

    Example

    In the example below, we access the various properties of the screen object with referencing the screen as the property of window object.

    <html><body><p> Screen Information </p><div id ="output"></div><script>
    
      document.getElementById("output").innerHTML ="screen height: "+ window.screen.height +"&lt;br&gt;"+"screen width: "+ window.screen.width +"&lt;br&gt;"+"screen colorDepth: "+ window.screen.colorDepth +"&lt;br&gt;"+"screen pixelDepth: "+ window.screen.pixelDepth +"&lt;br&gt;"+"screen availHeight: "+ window.screen.availHeight +"&lt;br&gt;"+"screen availWidth: "+ window.screen.availWidth;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Screen Information
    screen height: 864
    screen width: 1536
    screen colorDepth: 24
    screen pixelDepth: 24
    screen availHeight: 816
    screen availWidth: 1536
    

    Example

    In the below code, we access the various properties of the screen object and observe their value. In this example we are not referencing the window object to access the screen object.

    <html><body><p> Screen Information </p><div id ="output"></div><script>
    
      document.getElementById("output").innerHTML ="screen height: "+ screen.height +"&lt;br&gt;"+"screen width: "+ screen.width +"&lt;br&gt;"+"screen colorDepth: "+ screen.colorDepth +"&lt;br&gt;"+"screen pixelDepth: "+ screen.pixelDepth +"&lt;br&gt;"+"screen availHeight: "+ screen.availHeight +"&lt;br&gt;"+"screen availWidth: "+ screen.availWidth;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Screen Information
    screen height: 864
    screen width: 1536
    screen colorDepth: 24
    screen pixelDepth: 24
    screen availHeight: 816
    screen availWidth: 1536
    

    Please note that we get the same information about the screen in the above two examples.

    Screen Object Properties List

    Below, we have covered all properties of the 'screen' object with a description. You need to use the 'screen' as a reference to access these properties.

    PropertyDescription
    availHeightIt gives the height of the screen without including the taskbar.
    availWidthIt gives the width of the screen without including the taskbar.
    colorDepthIt gives the depth of the color palette to display images.
    heightIt returns the total height of the screen.
    pixelDepthIt is used to get the color resolution of the screen.
    widthTo get the total width of the screen.

  • Document Object

    Window Document Object

    The document object is a JavaScript object that provides the access to all elements of an HTML document. When the HTML document is loaded in the web browser, it creates a document object. It is the root of the HTML document.

    The document object contains the various properties and methods you can use to get details about HTML elements and customize them.

    The JavaScript document object is a property of the window object. It can be accessed using window.document syntax. It can also be accessed without prefixing window object.

    JavaScript Document Object Properties

    The JavaScript Document Object represents the entire HTML document, and it comes with several properties that allow us to interact with and manipulate the document. Some common Document object properties are as follows

    • document.title − Gets or sets the title of the document.
    • document.URL − Returns the URL of the document.
    • document.body − Returns the <body> element of the document.
    • document.head − Returns the <head> element of the document.
    • document.documentElement − Returns the <html> element of the document.
    • document.doctype − Returns the Document Type Declaration (DTD) of the document.

    These properties provide a way to access and modify different parts of the HTML document using JavaScript.

    Example: Accessing the document title

    In the example below, we use the document.title property to access the property odd the document.

    <html><head><title> JavaScript -DOM Object </title></head><body><div id ="output">The title of the document is:</div><script>
    
      document.getElementById("output").innerHTML += document.title;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The title of the document is: JavaScript - DOM Object
    

    Example: Accessing the document URL

    In the example below, we have used the document.URL property to access the current URL of the page.

    <html><head><title> JavaScript -DOM Object </title></head><body><div id ="output">The URLof the document is:</div><script>
    
      document.getElementById("output").innerHTML += document.URL;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The URL of the document is: https://www.tutorialspoint.com/javascript/javascript_document_object.htm
    

    JavaScript Document Object Methods

    The JavaScript Document Object provides us with various methods that allow us to interact with and manipulate the HTML document. Some common Document object methods are as follows

    • getElementById(id) − Returns the element with the specified ID.
    • getElementsByClassName(className) − Returns a collection of elements with the specified class name.
    • getElementsByTagName(tagName) − Returns a collection of elements with the specified tag name.
    • createElement(tagName) − Creates a new HTML element with the specified tag name.
    • createTextNode(text) − Creates a new text node with the specified text.
    • appendChild(node) − Appends a node as the last child of a node.
    • removeChild(node) − Removes a child node from the DOM.
    • setAttribute(name, value) − Sets the value of an attribute on the specified element.
    • getAttribute(name) − Returns the value of the specified attribute on the element.

    These methods enable us to dynamically manipulate the structure and content of the HTML document using JavaScript.

    Example: Accessing HTML element using its id

    In the example below, we use document.getElementById() method to access the DIV element with id "output" and then use the innerHTML property of the HTML element to display a message.

    <html><body><div id ="result"></div><script>// accessing the DIV element.
       document.getElementById("result").innerHTML +="Hello User! You have accessed the DIV element using its id.";</script></body></html>

    Output

    Hello User! You have accessed the DIV element using its id.
    

    Example: Adding an event to the document

    In the example below, we use document.addEventListener() method to add a mouseover event to the document.

    <html><body><div id ="result"><h2> Mouseover Event </h2><p> Hover over here to change background color </p></div><script>
    
      document.addEventListener('mouseover',function(){
         document.getElementById("result").innerHTML ="Mouseover event occurred.";});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Document Object Properties List

    Here, we have listed all properties of the document object.

    PropertyDescription
    document.activeElementTo get the currently focused element in the HTML document.
    adoptedStyleSheetsIt sets the array of the newly constructed stylesheets to the document.
    baseURITo get the absolute base URI of the document.
    bodyTo set or get the documents <body> tag.
    characterSetTo get the character encoding for the document.
    childElementCountTo get a count of the number of child elements of the document.
    childrenTo get all children of the document.
    compatModeTo get a boolean value representing whether the document is rendered in the standard modes.
    contentTypeIt returns the MIME type of the document.
    cookieTo get the cookies related to the document.
    currentScriptIt returns the script of the document whose code is currently executing.
    defaultViewTo get the window object associated with the document.
    designModeTo change the editability of the document.
    dirTo get the direction of the text of the document.
    doctypeTo get the document type declaration.
    documentElementTo get the <html> element.
    documentURITo set or get the location of the document.
    embedsTo get all embedded (<embed>) elements of the document.
    firstElementChildTo get the first child element of the document.
    formsIt returns an array of <form> elements of the document.
    fullScreenElementTo get the element that is being presented in the full screen.
    fullScreenEnabledIt returns the boolean value, indicating whether the full screen is enabled in the document.
    headIt returns the <head> tag of the document.
    hiddenIt returns a boolean value, representing whether the document is considered hidden.
    imagesIt returns the collection of the <img> elements.
    lastElementChildIt returns the last child element of the document.
    lastModifiedTo get the last modified date and time of the document.
    linksTo get the collection of all <a> and <area> elements.
    locationTo get the location of the document.
    readyStateTo get the current state of the document.
    referrerTo get the URL of the document, which has opened the current document.
    scriptsTo get the collection of all <script> elements in the document.
    scrollingElementTo get the reference to the element which scrolls the document.
    styleSheetsIt returns the style sheet list of the CSSStyleSheet object.
    timeLineIt represents the default timeline of the document.
    titleTo set or get the title of the document.
    URLTo get the full URL of the HTML document.
    visibilityStateIt returns the boolean value, representing the visibility status of the document.

    Document Object Methods List

    The following is a list of all JavaScript document object methods −

    MethodDescription
    addEventListener()It is used to add an event listener to the document.
    adoptNode()It is used to adopt the node from the other documents.
    append()It appends the new node or HTML after the last child node of the document.
    caretPositionFromPoint()It returns the caretPosition object, containing the DOM node based on the coordinates passed as an argument.
    close()It closes the output stream opened using the document.open() method.
    createAttribute()It creates a new attribute node.
    createAttributeNS()It creates a new attribute node with the particular namespace URI.
    createComment()It creates a new comment node with a specific text message.
    createDocumentFragment()It creates a DocumentFragment node.
    createElement()It creates a new element node to insert into the web page.
    createElementNS()It is used to create a new element node with a particular namespace URI.
    createEvent()It creates a new event node.
    createTextNode()It creates a new text node.
    elementFromPoint()It accesses the element from the specified coordinates.
    elementsFromPoint()It returns the array of elements that are at the specified coordinates.
    getAnimations()It returns the array of all animations applied on the document.
    getElementById()It accesses the HTML element using the id.
    getElementsByClassName()It accesses the HTML element using the class name.
    getElementsByName()It accesses the HTML element using the name.
    getElementsByTagName()It accesses the HTML element using the tag name.
    hasFocus()It returns the boolean value based on whether any element or document itself is in the focus.
    importNode()It is used to import the node from another document.
    normalize()It removes the text nodes, which are empty, and joins other nodes.
    open()It is used to open a new output stream.
    prepand()It is used to insert the particular node before all nodes.
    querySelector()It is used to select the first element that matches the css selector passed as an argument.
    querySelectorAll()It returns the nodelist of the HTML elements, which matches the multiple CSS selectors.
    removeEventListener()It is used to remove the event listener from the document.
    replaceChildren()It replaces the children nodes of the document.
    write()It is used to write text, HTML, etc., into the document.
    writeln()It is similar to the write() method but writes each statement in the new line.

  • Window Object

    The JavaScript window object represents the browser’s window. In JavaScript, a ‘window’ object is a global object. It contains the various methods and properties that we can use to access and manipulate the 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. Furthermore, when the browser renders the content in the ‘iframe, it creates a separate ‘window’ object for the browser and each iframe.

    Here, you will learn to use the ‘window’ object as a global object and use the properties and methods of the window object.

    Window Object as a Global Object

    As ‘window’ is a global object in the web browser, you can access the global variables, functions, objects, etc., using the window object anywhere in the code.

    Let’s understand it via the example below.

    Example

    In the below code, we have defined the ‘num’ global and local variables inside the function. Also, we have defined the ‘car’ global object.

    In the test() function, we access the global num variable’s value using the ‘window’ object.

    <html><body><div id ="output1">The value of the global num variable is:</div><div id ="output2">The value of the local num variable is:</div><div id ="output3">The value of the car object is:</div><script>var num =100;const car ={
    
         brand:"Honda",
         model:"city",}functiontest(){let num =300;
         document.getElementById("output1").innerHTML += window.num;
         document.getElementById("output2").innerHTML += num;
         document.getElementById("output3").innerHTML += car.brand;}test();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The value of the global num variable is: 100
    The value of the local num variable is: 300
    The value of the car object is: Honda
    

    You may also use the 'window' object to make a particular variable global from a particular block.

    Window Object Properties

    The 'window' object contains the various properties, returning the status and information about the current window.

    Below, we have covered all properties of the 'window' object with a description. You may use the 'window' as a reference to access these properties.

    Property NameProperty Description
    closedWhen the particular window is closed, it returns true.
    consoleIt returns the window's console object.
    customElementsIt is used to define and access the custom elements in the browser window.
    devicePixelRatioIt returns the physical pixel ratio of the device divided by CSS pixel ratio.
    documentIt is used to access the HTML document opened in the current window.
    framesIt is used to get the window items like iframes, which are opened in the current window.
    frameElementIt returns the current frame of the window.
    historyIt is used to get the history object of the window.
    innerHeightIt returns the inner height of the window without including the scroll bar, toolbar, etc.
    innerWidthIt returns the inner width of the window without including the scroll bar, toolbar, etc.
    lengthIt returns the total number of iframes in the current window.
    localStorageIt is used to access the local storage of the current window.
    locationIt is used to access the location object of the current window.
    nameIt is used to get or set the name of the window.
    navigatorIt is used to get the Navigator object of the browser.
    openerIt returns a reference to the window from where the current window is opened.
    outerHeightIt returns the total height of the window.
    outerWidthIt returns the total width of the window.
    pageXOffsetIt returns the number of pixels you have scrolled the web page horizontally.
    pageYOffsetIt returns the number of pixels you have scrolled the web page vertically.
    parentIt contains the reference to the parent window of the current window.
    schedulerIt is entry point for using the prioritized task scheduling.
    screenIt returns the 'screen' object of the current window.
    screenLeftIt returns the position of the x-coordinate of the current window relative to the screen in pixels.
    screenTopIt returns the position of the y-coordinate of the current window relative to the screen in pixels.
    screenXIt is similar to the screenLeft property.
    screenYIt is similar to the screenTop property.
    scrollXIt is similar to the pageXOffset.
    scrollYIt is similar to the pageYOffset.
    selfIt is used to get the current state of the window.
    sessionStorageIt lets you access the 'sessionStorage' object of the current window.
    speechSynthesisIt allows you to use the web speech API.
    visualViewPortIt returns the object containing the viewport of the current window.
    topIt contains a reference to the topmost window.

    Here, we will cover some properties with examples.

    OuterHeight/OuterWidth Properties of the Window object

    The outerHeight property of the window object returns the window's height, and the outerWidth property of the window object returns the window's width.

    Example

    In the code below, we used the outerHeight and outerWidth property to get the dimensions of the window. You can change the size of the window and observe changes in the value of these properties.

    <html><body><p id ="output1">The outer width of the window is:</p><p id ="output2">The outer height of the window is:</p><script>const outerHeight = window.outerHeight;const outerWidth = window.outerWidth;
    
      document.getElementById("output1").innerHTML += outerWidth;
      document.getElementById("output2").innerHTML += outerHeight;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The outer width of the window is: 1536
    The outer height of the window is: 816
    

    ScreenLeft Property of the Window Object

    The window screenLeft property returns the left position of the current window.

    Example

    In the output of the below code, you can see the left position of the current window in pixels.

    <html><body><div id ="output">Your browser window is left by:</div><script>const screenLeft = window.screenLeft;
    
      document.getElementById("output").innerHTML += screenLeft +" px.";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Your browser window is left by: 0 px.
    

    Window Object Methods

    The 'window' object also contains methods like properties to manipulate the current browser window.

    In the below table, we have covered the methods of the 'window' object with their description. You may use 'window' as a reference to access and invoke the below methods to make the code readable.

    Method NameMethod Description
    alert()It is used to show the alert message to the visitors.
    atob()It converts the string into the base-64 string.
    blur()It removes the focus from the window.
    btoa()It decodes the base-64 string in the normal string.
    cancelAnimationFrame()It cancels the animation frame scheduled using the requestAnimationFrame() method.
    cancelIdleCallback()It cancels a callback scheduled with the requestIdCallback() method.
    clearImmediate()It is used to clear actions specified using the setImmediate() method.
    clearInterval()It resets the timer you have set using the setInterval() method.
    clearTimeout()It stops the timeout you have set using the setTimeOut() method.
    close()It is used to close the current window.
    confirm()It shows the confirm box to get the confirmation from users.
    focus()It focuses on the current active window.
    getComputedStyle()It returns the current window's computed CSS style.
    getSelection()It returns the selection object based on the selected text range.
    matchMedia()It returns a new MediaQueryList object, which you can use to check whether the document matches the media queries.
    moveBy()It changes the position of the window relative to the current position.
    moveTo()It changes the position of the window absolutely.
    open()It opens a new window.
    postMessage()It is used to send a message to a window.
    print()It lets you print the window.
    prompt()It allows you to show a prompt box to get user input.
    requestAnimationFrame()It helps you to tell the browser that you want to perform an animation so the browser can update the animation before the next repaint.
    requestIdleCallback()It sets the callback functions to be called when the browser is Idle.
    resizeBy()It resizes the window by a particular number of pixels.
    resizeTo()It changes the size of the window.
    scrollTo()It scrolls the window to the absolute position.
    scrollBy()It scrolls the window relative to the current position.
    setImmediate()It breaks up long-running operations and runs the callback function instantly when the browser completes other operations.
    setInterval()It is used to execute a particular action after every interval.
    setTimeout()It is used to execute a particular action after a particular time.
    stop()It stops the loading of window.

    Here, we will cover some methods with examples.

    JavaScript window.alert() Method

    The window.alert() method allows you to show the pop-up dialog containing the message, warning, etc. It takes the string text as an argument.

    Example

    In the below example, when you click the button, it will invoke the alert_func() function and show the pop-up box at the middle top.

    <html><body><button onclick ="alert_func()"> Execute Alert </button><script>functionalert_func(){
    
         window.alert("The alert_func funciton is executed!");}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    JavaScript window.open() Method

    The window.open() method is used to open a new window. It takes a URL as an argument, which you need to open in a new window.

    Example

    In the below code, we used the window.open() method to open a new window in the browser. You can see that the code opens the home page of the 'tutorialspoint' website in the new window.

    <html><body><button onclick ="openWindow()"> Open New Window </button><script>functionopenWindow(){
    
         window.open("https://www.tutorialspoint.com/");}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    JavaScript window.print() Method

    The window.print() method lets you print the web page.

    Example

    In the below code, click the button to print the web page.

    <html><body><h2> Hello World!</h2><button onclick ="printPage()"> Print Webpage </button><script>functionprintPage(){
    
         window.print();}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>