What is the difference between document.location.href and document.location?
Solution 1:
document.location
is a synonym for window.location
that has been deprecated for almost as long as JavaScript has existed. Don't use it.
location
is a structured object, with properties corresponding to the parts of the URL. location.href
is the whole URL in a single string. Assigning a string to either is defined to cause the same kind of navigation, so take your pick.
I consider writing to location.href = something
to be marginally better as it's slightly more explicit about what it's doing. You generally want to avoid just location = something
as it looks misleadingly like a variable assignment. window.location = something
is fine though.
Solution 2:
The document.location
is an object that contains properties for the current location.
The href
property is one of these properties, containing the complete URL, i.e. all the other properties put together.
Some browsers allow you to assign an URL to the location
object and acts as if you assigned it to the href
property. Some other browsers are more picky, and requires you to use the href
property. Thus, to make the code work in all browsers, you have to use the href
property.
Both the window
and document
objects has a location
object. You can set the URL using either window.location.href
or document.location.href
. However, logically the document.location
object should be read-only (as you can't change the URL of a document; changing the URL loads a new document), so to be on the safe side you should rather use window.location.href
when you want to set the URL.
Solution 3:
typeof document.location; // 'object'
typeof document.location.href; // 'string'
The href
property is a string, while document.location
itself is an object.
Solution 4:
document.location
is an object, while document.location.href
is a string. But the former has a toString
method, so you can read from it as if it was a string and get the same value as document.location.href
.
In some browsers - most modern ones, I think - you can also assign to document.location
as if it were a string. According to the Mozilla documentation however, it is better to use window.location
for this purpose as document.location
was originally read-only and so may not be as widely supported.
Solution 5:
document.location is deprecated in favor of window.location, which can be accessed by just location, since it's a global object.
The location object has multiple properties and methods. If you try to use it as a string then it acts like location.href.