How to set location and location.href using JavaScript?

The window.location object in JavaScript provides methods to get and set the current page URL. You can redirect users to different pages using either location or location.href properties.

The window.location object can be written without the window prefix. Common location properties include:

  • location.href ? Gets or sets the complete URL

  • location.hostname ? Gets the domain name

  • location.protocol ? Gets the protocol (http: or https:)

  • location.pathname ? Gets the path portion of the URL

  • location.assign() ? Loads a new document

Syntax

The following syntax shows how to set location and location.href:

location = "URL"
// or
location.href = "URL"

Parameters

  • URL ? A string specifying the destination URL

Using location Property

This example demonstrates setting location directly when a button is clicked:

<html>
    <body>
        <h2>Setting Location using JavaScript</h2>
        <p>Click the button to go to TutorialsPoint</p>
        <button onclick="myLocation()">
            Click Here to Navigate
        </button>

        <script>
            function myLocation() {
                location = "https://www.tutorialspoint.com/";   
            }
        </script>
    </body>
</html>

Using location.href Property

This example shows how to use location.href to redirect to a different URL:

<html>
    <body>
        <h2>Setting Location using location.href</h2>
        <button onclick="hrefLocation()">
            Click Here to Navigate
        </button>
        
        <script>
            function hrefLocation() {
                location.href = "https://www.tutorialspoint.com/";   
            }
        </script>
    </body>
</html>

Comparison

Method Usage Browser History
location = URL Direct assignment Adds entry to history
location.href = URL More explicit Adds entry to history
location.replace(URL) Replace current page Does not add to history

Alternative Methods

You can also use other location methods for navigation:

<script>
    // Using assign() method
    function assignLocation() {
        location.assign("https://www.tutorialspoint.com/");
    }
    
    // Using replace() method (doesn't add to history)
    function replaceLocation() {
        location.replace("https://www.tutorialspoint.com/");
    }
</script>

Conclusion

Both location and location.href effectively redirect users to new URLs. Use location.replace() when you don't want to add the current page to browser history.

Updated on: 2026-03-15T23:19:00+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements