Advance JavaScript (DOM, BOM, Web API) / Browser Object Model (BOM)

Location

πŸ“Œ What is location?

The location object provides information about the current URL

and allows JavaScript to redirect, reload, or modify the browser URL.

πŸ‘‰ It is part of the BOM and accessed via window.location.

window.location === location // true

🌐 URL Structure

For this URL:

<https://www.example.com:8080/path/page.html?id=10#top>

Property

Value

protocol

https:

hostname

www.example.com

port

8080

pathname

/path/page.html

search

?id=10

hash

#top


🧩 Common location Properties

Example Taken: https://www.example.com:8080/path/page.html?id=10#top

1️⃣ location.href

console.log(location.href);

Explanation:

Returns the full URL of the current page.

https://www.example.com:8080/path/page.html?id=10#top

2️⃣ location.protocol

console.log(location.protocol);

Explanation:

Returns the protocol used.

https:

3️⃣ location.hostname

console.log(location.hostname);

Explanation:

Returns the domain name (no port).

www.example.com

4️⃣ location.port

console.log(location.port);

Explanation:

Returns the port number. Empty string if default (80 / 443).

8080

5️⃣ location.pathname

console.log(location.pathname);

Explanation:

Returns the path after the domain.

/path/page.html

6️⃣ location.search

console.log(location.search);

Explanation:

Returns query parameters.

?id=10

7️⃣ location.hash

console.log(location.hash);

Explanation:

Returns the URL fragment (used for anchors).

#top

πŸ”„ location Methods

1️⃣ location.reload()

location.reload();

Explanation:

Reloads the current page.

  • location.reload() β†’ normal reload

  • location.reload(true) β†’ force reload (from server)

Output:

πŸ”„ Page refreshes

2️⃣ location.assign()

location.assign("<https://google.com>");

Explanation:

Navigates to a new URL

βœ”οΈ Adds entry to browser history

Output:

➑️ Redirects to Google

3️⃣ location.replace()

location.replace("<https://google.com>");

Explanation:

Redirects to a new URL

❌ Does NOT add entry to history

Output:

➑️ Redirects (Back button won’t work)


πŸ†š assign() vs replace()

Method

Back Button

assign()

βœ… Works

replace()

❌ Disabled


🎯 Modify URL Parts

location.pathname = "/login";

Explanation:

Changes path and reloads page.

Output:

➑️ Navigates to /login


⭐ Important Notes

  • location causes page reloads

  • Changing any property triggers navigation

  • Widely used for redirects & URL handling


βœ… Summary

  • location controls the URL

  • Used for redirects, reloads, and reading URL data

  • Part of BOM, under window