The location Object

Welcome to our free JavaScript tutorial. This tutorial is based on Webucator's Introduction to JavaScript Training course.

Contact Us or call 1-877-932-8228
The location Object

The location Object

location Properties
Property Description
href Returns the full location of the page. The value can be set to change the page.
protocol Returns the protocol used to deliver the page (e.g., "http").
host Returns the host of the page (e.g., ""). It will include the port if included.
hostname Returns the host of the page (e.g., ""), but not the port.
port Returns the port of the host if included (e.g., "80").
pathname Returns the path after the domain name (e.g., "/webdesign/javascript.cfm" for
search Returns the querystring, including the question mark (e.g., "?q=javascript+training" for
hash Returns the hash, including the hash mark (e.g., "#dom-location-hash" for
location Methods
Method Description
assign(url) Navigates to the url argument. Same as location.href=url;.
replace(url) Replaces the current page in the history stack with the url argument.
reload() Reloads the page.

The properties and methods above are demonstrated in the following code sample:

Code Sample:

<meta charset="UTF-8">
<title>Location Info</title>
<h1>location Object Properties</h1>
	<li><a href="?firstName=Nat">Add Search</a></li>
	<li><a href="#props">Add Hash</a></li>
	<li><a href="javascript:location.replace('#props')">Add Hash with <code>replace()</code></a></li>
	<li><a href="javascript:location.assign('#props')">Add Hash with <code>assign()</code></a></li>
	<li><a href="javascript:location.reload()">Reload</a></li>
	<li><a href="location.html">Start Over</a></li>

<ol id="props">
	<li>href: <strong><script>document.write(location.href);</script></strong></li>
	<li>protocol: <strong><script>document.write(location.protocol);</script></strong></li>
	<li>host: <strong><script>document.write(;</script></strong></li>
	<li>hostname: <strong><script>document.write(location.hostname);</script></strong></li>
	<li>port: <strong><script>document.write(location.port);</script></strong></li>
	<li>pathname: <strong><script>document.write(location.pathname);</script></strong></li>
	<li>search: <strong><script>document.write(;</script></strong></li>
	<li>hash: <strong><script>document.write(location.hash);</script></strong></li>
	<li>history.length: <strong><script>document.write(history.length);</script></strong></li>

Code Explanation

Most of the location properties and methods above are only used in advanced applications that require customizing how the site/application responds to the user pressing the Back and Forward buttons. The exception is the href property, which is commonly used to create "button links" as you'll see in the exercise that follows:


This tutorial is based on Webucator's Introduction to JavaScript Training Course. We also offer many other JavaScript Training courses. Sign up today to get help from a live instructor.