What is the difference between window.Location and window.location.href?

Asked

Viewed 1,560 times

13

I’ve always used window.location.href to redirect to another internal page or external URL, but when using only window.location (without the .href) produces the same result, i.e., makes the same redirect.

Example with window.location:

function redir(){
   window.location = "./";
}
<button onclick="redir()">Ir</button>

Example with window.location.href:

function redir(){
   window.location.href = "./";
}
<button onclick="redir()">Ir</button>

With this raised me the doubt: what is the difference between the two instructions and when to use one or the other?

2 answers

18

window.location is an object that contains all information about the current location of the document (host, href, port, Protocol, etc.), ie is a complete object and can use to operate in various ways with each individual information. Documentation.

window.location.href is just one string with the full URL of the current site when all you need is just the textual representation of the URL.

They act the same way when you assign a URL to them - they redirect to the page you assign, but you can see differences between them when you open the browser console (Firebug or Developer Tools) and write window.location and window.location.href. Documentation.

Source.

11


  • window.Location = It refers to the window Location object, you can use it when you need to use the whole object, or more than one property of it.
  • window.location.href = It is specifically to the href attribute of Location. (String)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.