Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between window.location and location.href

Tags:

javascript

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?

like image 574
Mulesoft Developer Avatar asked Mar 28 '12 08:03

Mulesoft Developer


People also ask

What is window location href?

Window Location Href The window.location.href property returns the URL of the current page.

What is the difference between window location and document location?

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).

What does window location mean?

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.


2 Answers

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.

like image 147
Mateusz W Avatar answered Sep 27 '22 20:09

Mateusz W


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.

like image 34
James Lawruk Avatar answered Sep 27 '22 22:09

James Lawruk