JavaScript

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript Location Object


The JavaScript Location object is a powerful part of the Browser Object Model that gives you direct access to the current URL of a web page. It allows developers to read information from the browser address bar and also control navigation behavior like redirecting users, reloading pages, or moving to different URLs. Understanding the Location object is essential for building dynamic, interactive, and navigation-aware web applications.

In this tutorial, you will learn what the JavaScript Location object is, how it works, its properties and methods, practical examples, common mistakes, best practices, and real-world use cases.

What Is the JavaScript Location Object

The Location object contains information about the current page URL and provides methods to change that URL. It is available through:

window.location

Since window is the global object in browsers, you can also access it directly as:

location

The Location object reflects exactly what you see in the browser’s address bar and lets JavaScript interact with it safely and efficiently.

Why the Location Object Is Important

The Location object is important because it allows you to:

  • Read the current page URL and its parts

  • Redirect users to another page

  • Reload the current page programmatically

  • Pass data using query parameters

  • Handle routing logic in web applications

  • Build login redirects, logout flows, and dashboards

Most real-world websites rely on the Location object for navigation and state handling.

Common Properties of the Location Object

The Location object provides several useful properties that represent different parts of a URL.

Assume the current URL is:

https://www.example.com:8080/products/item.html?id=25#reviews

location.href

Returns the full URL.

console.log(location.href);

Output includes protocol, domain, path, query string, and hash.

location.protocol

Returns the protocol used.

console.log(location.protocol);

Output:

https:

location.hostname

Returns the domain name.

console.log(location.hostname);

Output:

www.example.com

location.port

Returns the port number.

console.log(location.port);

If no port is specified, it returns an empty string.

location.pathname

Returns the path of the URL.

console.log(location.pathname);

Output:

/products/item.html

location.search

Returns the query string.

console.log(location.search);

Output:

?id=25

This is commonly used to read data passed through URLs.

location.hash

Returns the fragment identifier.

console.log(location.hash);

Output:

#reviews

This is often used for page anchors and single-page applications.

Location Object Methods

The Location object also provides methods that allow navigation control.

location.assign()

Loads a new document at the specified URL.

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

This keeps the current page in browser history.

location.replace()

Replaces the current page with a new one.

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

The current page is removed from browser history, so the user cannot go back.

location.reload()

Reloads the current page.

location.reload();

You can force a reload from the server by passing true.

location.reload(true);

Reading Query Parameters Using Location

Query parameters are commonly used to pass data between pages.

let params = new URLSearchParams(location.search);
let productId = params.get("id");

console.log(productId);

This approach is clean, readable, and widely supported.

Practical Examples

Example 1: Redirect After Login

let isLoggedIn = true;

if (isLoggedIn) {
    location.href = "/dashboard.html";
}

This pattern is common in authentication systems.

Example 2: Reload Page After Form Submission

document.getElementById("submitBtn").addEventListener("click", () => {
    location.reload();
});

Useful when you want to refresh data after user actions.

Example 3: Extract Query Data

let params = new URLSearchParams(location.search);
let name = params.get("name");

if (name) {
    document.getElementById("welcome").innerText = "Welcome " + name;
}

This is often used for personalized messages.

Example 4: Scroll to Section Using Hash

if (location.hash === "#contact") {
    document.getElementById("contact").scrollIntoView();
}

This works well for landing pages.

Example 5: Conditional Redirect Based on Protocol

if (location.protocol !== "https:") {
    location.replace("https://" + location.hostname + location.pathname);
}

Commonly used to enforce secure connections.

Difference Between assign, replace, and href

Although these methods seem similar, their behavior differs.

  • location.href navigates and keeps history

  • location.assign() navigates and keeps history

  • location.replace() navigates without keeping history

Choosing the right method improves user experience.

Common Mistakes

  • Forgetting that replace() removes history

  • Assuming query parameters are automatically parsed

  • Reloading pages unnecessarily

  • Modifying URL parts incorrectly

  • Ignoring encoding of special characters

These mistakes can cause navigation bugs or poor UX.

Best Practices

  • Use URLSearchParams for query handling

  • Prefer replace() for redirects after logout

  • Avoid excessive reloads

  • Validate URLs before redirecting

  • Keep navigation logic simple and predictable

Following these practices leads to smoother applications.

Real-World Applications

The JavaScript Location object is used in:

  • Login and logout flows

  • Dashboards and admin panels

  • Single-page application routing

  • Payment and checkout redirects

  • Tracking campaigns using URL parameters

  • Language and region-based redirects

Almost every production website relies on the Location object in some form.

Security Considerations

While using the Location object:

  • Avoid redirecting to untrusted URLs

  • Validate query parameters

  • Prevent open redirect vulnerabilities

  • Do not expose sensitive data in URLs

Security awareness is critical when dealing with navigation.

Summary of JavaScript Location Object

The JavaScript Location object gives developers full control over reading and manipulating the browser URL. By understanding its properties and methods, you can build smart navigation systems, handle redirects, manage query parameters, and create responsive user flows. Whether you are working on a simple website or a complex web application, mastering the Location object is an essential JavaScript skill.


Practice Questions

  1. How can you get the full URL of the current webpage using the location object?

  2. Write a script to display the protocol (http: or https:) and hostname of the current page.

  3. How can you redirect a user to https://www.google.com using location.href?

  4. What is the difference between location.href and location.replace() when redirecting a page? Give an example.

  5. Write code to reload the current page when a button is clicked using location.reload().

  6. How can you access and display the pathname and port number of the current URL?

  7. If a URL contains query parameters like ?id=123&name=Vicky, how can you extract the values of id and name?

  8. How can you detect and log the hash part of the URL (e.g., #contact) and scroll to the corresponding section?

  9. Write code to dynamically change the URL hash to #about without reloading the page.

  10. Create a simple page with two buttons: one redirects to a new page, and the other reloads the current page using the location object.


Try a Short Quiz.

No quizzes available.


JavaScript

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top