-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
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 Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
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.
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.
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.
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
Returns the full URL.
console.log(location.href);
Output includes protocol, domain, path, query string, and hash.
Returns the protocol used.
console.log(location.protocol);
Output:
https:
Returns the domain name.
console.log(location.hostname);
Output:
www.example.com
Returns the port number.
console.log(location.port);
If no port is specified, it returns an empty string.
Returns the path of the URL.
console.log(location.pathname);
Output:
/products/item.html
Returns the query string.
console.log(location.search);
Output:
?id=25
This is commonly used to read data passed through URLs.
Returns the fragment identifier.
console.log(location.hash);
Output:
#reviews
This is often used for page anchors and single-page applications.
The Location object also provides methods that allow navigation control.
Loads a new document at the specified URL.
location.assign("https://www.google.com");
This keeps the current page in browser history.
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.
Reloads the current page.
location.reload();
You can force a reload from the server by passing true.
location.reload(true);
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.
let isLoggedIn = true;
if (isLoggedIn) {
location.href = "/dashboard.html";
}
This pattern is common in authentication systems.
document.getElementById("submitBtn").addEventListener("click", () => {
location.reload();
});
Useful when you want to refresh data after user actions.
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.
if (location.hash === "#contact") {
document.getElementById("contact").scrollIntoView();
}
This works well for landing pages.
if (location.protocol !== "https:") {
location.replace("https://" + location.hostname + location.pathname);
}
Commonly used to enforce secure connections.
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.
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.
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.
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.
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.
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.
How can you get the full URL of the current webpage using the location object?
Write a script to display the protocol (http: or https:) and hostname of the current page.
How can you redirect a user to https://www.google.com using location.href?
What is the difference between location.href and location.replace() when redirecting a page? Give an example.
Write code to reload the current page when a button is clicked using location.reload().
How can you access and display the pathname and port number of the current URL?
If a URL contains query parameters like ?id=123&name=Vicky, how can you extract the values of id and name?
How can you detect and log the hash part of the URL (e.g., #contact) and scroll to the corresponding section?
Write code to dynamically change the URL hash to #about without reloading the page.
Create a simple page with two buttons: one redirects to a new page, and the other reloads the current page using the location object.
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 Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
