How to Get the Port Number in JavaScript

Learn about the fastest and most practical way to get the port number of the current URL in JavaScript, without the B.S.

Published Categorized as JavaScript

Suppose you’re building a web app in JavaScript, and your web app’s logic needs to factor in the port number of the current URL.

To get the port number of the current URL in JavaScript, you need to reference the window.location.port property of the Window object.

The Window object, for those of you coming across it for the first time, is the parent object of all other elements on the page, and it allows you to reference the DOM, navigational and history objects, and a number of other read-only properties.

Here’s how to get the port number:

let currentPort = window.location.port;
console.log(currentPort)

If the current URL contains a port number, then the window.location.port property will return it. For example, https://example.com:8080 would return a string of “8080”. And if there’s no port number in the URL, the window.location.port property will have an empty string (“”) for a value.

Knowing this, you could create an expression that checks if the property’s value is a truthy or not:

if(window.location.port) {
    // Do this if the port number is not an empty string (there's a port number in the URL)
} else {
    // Do this if the port number is an empty string (there's no port number in the URL)
}

Or a function that returns the port number only if it’s present in the URL:

function getPortNumber() {
    const currentPort = window.location.port;
    if(currentPort) {
        return currentPort
    }
}

If you need to get the port number only once, it’s okay to reference the window.location.port property directly and not overengineer it. But if you need to reference it repeatedly, consider storing it in a constant or variable so that it will be stored in the memory and ready for you to use at lower computing cost.

By Dim Nikov

Editor of Maker's Aid. Part programmer, part marketer. Making things on the web and helping others do the same since the 2000s. Yes, I had Friendster and Myspace.

Leave a comment

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