🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to JavaScript Notes
Topic #160

JS Location


The window.location object can be used to get the current page address (URL) and to redirect the browser to a new page.


Window Location

The window.location object can be written without the window prefix.

Some examples:

  • window.location.href returns the href (URL) of the current page
  • window.location.hostname returns the domain name of the web host
  • window.location.pathname returns the path and filename of the current page
  • window.location.protocol returns the web protocol used (http: or https:)
  • window.location.assign() loads a new document

Window Location Href

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

Example

 document.getElementById("demo").innerHTML =
"Page location is " + window.location.href;

Window Location Hostname

The window.location.hostname property returns the name of the internet host (of the current page).

Example

 document.getElementById("demo").innerHTML =
"Page hostname is " + window.location.hostname;

Window Location Pathname

The window.location.pathname property returns the pathname of the current page.

Example

  document.getElementById("demo").innerHTML =
"Page path is " + window.location.pathname;

Window Location Protocol

The window.location.protocol property returns the web protocol of the page.

Example

 document.getElementById("demo").innerHTML =
"Page protocol is " + window.location.protocol;

Window Location Port

The window.location.port property returns the number of the internet host port (of the current page).

Example

 document.getElementById("demo").innerHTML =
"Port
  number is " + window.location.port;

Note: Most browsers will not display default port numbers (80 for http and 443 for https)


Window Location Assign

The window.location.assign() method loads a new document.

Example

<html>

<head>

<script>

function newDoc() {
  window.location.assign("https://www.w3schools.com")

 }

</script>

</head>

<body>

<input type="button" value="Load new document"
onclick="newDoc()">

</body>

</html>

Want to go beyond the notes?

Join CodingNow 2.0's JavaScript course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

JS Location – FAQs

Quick answers about learning JS Location in JavaScript.

This free note from CodingNow 2.0 explains JS Location in JavaScript — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every JavaScript topic on CodingNow 2.0, including JS Location, is 100% free with no signup required.
With focused practice, most students grasp JS Location in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now