Tuesday , 18 June 2019
Home / Programming / JavaScript / Location Object – Advanced JavaScript Tutorial
Location Object
Location Object

Location Object – Advanced JavaScript Tutorial

The location object contains information about the current URL you’re visiting. It can give you helpful information such as the port number, whether or not the site is using SSL and even allows you to redirect the user.


Clear your script and add this bit of code.

There are a couple of properties of the location object, but we’ll just focus on these 6.

  • hostname – This will return the server. This is usually the URL. For example, this would return www.jaskokoyn.com if this was hosted on my site.
  • href – This will return the full URL of the current page you’re on.
  • pathname – This will return the path of the URL. For example, if you’re on www.yoursite.com/path1/path2/index.html, then you would get /path1/path2/index.html
  • port – Returns the current port being used to access the website. Most of the time you’ll get an empty string if the port isn’t present in the URL.
  • protocol – Returns http: or https: depending if the server has SSL active or not.
  • search – This will return the query of the URL. This is usually the text after the ? in the URL if there is one.

Some of these may return an empty string depending if you’re opening this from an actual site or just opening it in your browser as a file.


One of the most common uses of the location object is to navigate to a new URL. To navigate to a new URL you use the assign() method. You simply pass in the new URL you would like to go to. Add this bit of code to your script.

There’s also another method that does the same thing called replace(). However, this method doesn’t allow the browser to save the previous URL. So the user can’t press the back button. Here’s how you would use it.

Finally, the last method that you can use is the reload() method. This method just refreshes the current page. This method has 1 parameter which is whether or not to reload from the server. When you visit a website, you get a cache copy so it’ll load faster the next time you visit it. However, you can force JavaScript to load a new copy of the current URL. Here’s how you would use it.


The location object can you help you manipulate the URL and redirect the user on certain conditions. For more information about the location object, then go here.


About Jasko Koyn

Check Also


Audio – Advanced JavaScript Tutorial

The video and audio objects both have the same events, properties and methods. So, you …

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.