I am confused as to the difference between
location.href. Both appear to be acting in the same way.
What is the difference?
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
They are different.
window.location is an object containing the property
href which is a string.
window.location.href behave differently because the former is an object and the latter is a string. If you run string functions like
toLowerCase(), you have to use
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
Check this old MDN article:
Location objects have a toString method returning the current URL. You can also assign a string to window.location. This means that you can work with window.location as if it were a string in most cases. Sometimes, for example when you need to call a String method on it, you have to explicitly call toString:
window is just the global object that houses several properties, one of them is
location also has properties, one of them is
location.href is just
location.href property returns the entire URL of the current page.
window.location property represents the currect location of the window object, if you change this you will get redirected.
You are accessing the same object. Its some kind of a shortcut. If you use firebug (or similar) to change its "hash" property, you'll see that it gets changed in both places.
Technically, your default scope is the window object, so when you access "location.href" you are accessing to window.location.href.
©2020 All rights reserved.