I am confused as to the difference between window.location
and location.href
. Both appear to be acting in the same way.
What is the difference?
Window Location Href The window.location.href property returns the URL of the current page.
window. location is read/write on all compliant browsers. document. location is read-only in Internet Explorer (at least), but read/write in Gecko-based browsers (Firefox, SeaMonkey).
The location property of a window (i.e. window. location ) is a reference to a Location object; it represents the current URL of the document being displayed in that window. Since window object is at the top of the scope chain, so properties of the window.
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
.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With