Location

The location property of both window and document objects refers to the location object, which represents the current URL of the document and is similar to the URL object. You can create a URL object from the location object by passing the location object into the URL constructor.

const url = new URL(window.location);

The location object has the hash property that returns the fragment identifier portion of the URL, which is a hash mark (#) followed by an element ID. The search property returns the portion of the URL that starts with a question mark. Also, the document.URL property contains a string value of the current document URL.

const hash = window.location.hash;
const query = window.location.search;
document.URL; // => 'http://localhost:3000/'

If you assign a string to window.location or document.location, the browser will replace the document with the new one loaded from the provided URL.

window.location = "https://romanakchurin.com";
document.location = "page2.html"; // Relative redirect
if (!location.search) location.search = "?article=" + 3;

Setting the Location object to the fragment identifier scrolls the document to the element with the specified identifier. The #top identifier points to the top of the page by default.

location.hash = "section1";
location = "#top"; // Jump to the top of the document

The assign() method loads the document with provided URL and saves the current document in browser's history, while the replace() method redirects to the provided URL and erases the current document from the history. The reload() method reloads the current document.

// Redirect and save in history
location.assign("page3.html");

// Redirect and erase from history
location.replace("page4.html");

// Reload the current page
location.reload();