Difference between window.location and location.href
Solution 1:
window.location
is an object that holds all the information about the current document location (host, href, port, protocol etc.).
location.href
is shorthand for window.location.href (you call location from global object - window, so this is window.location.href), and this is only a string with the full URL of the current website.
They act the same when you assign a URL to them - they will redirect to the page which you assign, but you can see differences between them when you open the browser console (firebug or developer tools) and write window.location
and location.href
.
Solution 2:
They are different. window.location
is an object containing the property href
which is a string.
Setting window.location
and window.location.href
behave the same way, as you noticed, because it was built into the JavaScript language long ago. Read more in this question about setting window.location.
Getting window.location
and window.location.href
behave differently because the former is an object and the latter is a string. If you run string functions like indexOf()
or toLowerCase()
, you have to use window.location.href
.
Solution 3:
window.location
has other properties aside from href
but if you assign window.location
a URL it will redirect.
You can see all of its properties in MDN (like search
, protocol
, hash
, ...)