# Introduction to JavaScript Location Object

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Sep 18, 2021. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-location-object

> A quick guide to learn bout the JavaScript location object, and how to use it to get the current URL.

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:

```javascript
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:

```javascript
// 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:

```javascript
// 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();
```
