Introduction to JavaScript Location Object

In JavaScript, the window.location read-only property returns a Location object that represents the current URL of the document being displayed in that window.

The Location object can be used to get the current page URL, navigate to a new page, reload the current page, get different parts of the URL (hostname, protocol, etc.), and much more.

The following example demonstrates how the window.location.href property can be used to get the entire URL of the current web page:

const url = window.location.href;

console.log(url);
// https://attacomsian.com/blog/javascript-location-object/

Since window is the global object representing the window in which the script is running, you can access the Location object with it. For example, the window.location.href can be written as location.href.

Similarly, you can use other properties of the Location object such as host, hostname, port, protocol, pathname, search, and hash to access different parts of the URL:

// Get hostname with port (localhost or localhost:8080)
console.log(location.host);

// Get hostname (localhost or www.domain.com)
console.log(location.hostname);

// Get protocol (http or https)
console.log(location.protocol);

// Get port number (8080)
console.log(location.port);

// Get pathname (/javascript-tutorials/)
console.log(location.pathname);

// Get query string (?q=object)
console.log(location.search);

// Get URL fragment identifier (#trending)
console.log(window.location.hash);

Besides the above mentioned properties, the Location object also provides several methods such as assign(), reload(), and replace() to manipulate the current URL:

// Load new URL
location.assign(`https://attacomsian.com`);

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

// Load new URL with session history
location.replace(`https://youtube.com`);

// Print complete URL (same as location.href)
location.toString();

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.