What is the DOM Location object?

In JavaScript, the DOM Location object is part of the window object and contains information about the current URL. It can be accessed through the window.location property.

Properties of the Location object

1. hash

It returns the anchor part of the current URL, including the #.

Example

Assuming that the URL is https://educative.io:43/shot?q=location#example.

console.log(location.hash); 
// will return: #example

2. host

It returns the hostname, a : (colon), and port number of the current URL.

Example

Assuming that the URL is https://educative.io:43/shot?q=location#example.

console.log(location.host); 
// will return: educative.io:43

3. port

It returns the port number of the current URL.

Example

Assuming that the URL is https://educative.io:43/shot?q=location#example.

console.log(location.port); 
// will return: 43

4. hostname

It returns the hostname of the current URL.

Example

Assuming that the URL is https://educative.io:43/shot?q=location#example.

console.log(location.hostname); 
// will return: educative.io

5. protocol

It returns the protocol of the current URL.

Example

Assuming that the URL is https://educative.io:43/shot?q=location#example.

console.log(location.protocol); 
// will return: https

6. origin

It returns the protocol of the current URL.

Example

Assuming that the URL is https://educative.io:43/shot?q=location#example.

console.log(location.origin); 
// will return: https

7. pathname

It returns the pathname of the current URL.

Example

Assuming that the URL is https://educative.io:43/shot?q=location#example.

console.log(location.pathname); 
// will return: /shot

8. search

It returns the query string part of the current URL.

Example

Assuming that the URL is https://educative.io:43/shot?q=location#example.

console.log(location.search); 
// will return: ?q=location

9. href

It returns the current URL.

Example

Assuming that the URL is https://educative.io:43/shot?q=location#example.

console.log(location.href); 
// will return: https://educative.io:43/shot?q=location#example

Methods of the Location object

1. assign()

It loads a new document at the URL provided in the parameter.

Example
location.assign('https://shubhamkshatriya25.github.io/');

2. reload()

It reloads the URL, just like a refresh.

Example
location.reload();

3. replace()

It replaces the current URL with a new URL provided in the parameter.

Example
location.replace('https://shubhamkshatriya25.github.io/');

Free Resources