JavaScript Location port Tutorial

In this section, we will learn what the location port number is and how to use it in JavaScript.

What is port?

In short, port is a number!

You see, computers have a number assigned to them when they connect to the internet (This happens all the time behind the scene without us knowing!). This is known as the IP (Internet Protocol) and each computer gets its own unique IP.

Now computers can communicate with each other on the internet and this is happening because of this IP number!

For example, when you open the Google homepage, your browser basically finds the address (IP) of the Google and sends a request to that IP (Hence the computer that owns the IP which is known as a server) to get a file that we know it as the home page of Google.

Now, on a computer, there might be multiple applications that need to send a request to another computer (server) over the internet! For example, if you have an anti-virus, Internet browser, a chat application like Skype or Facebook etc. all of these applications behind the scene are constantly connecting to the internet!

Now if you think about it, there is one computer (For example, yours) and multiple applications running in that computer! When a request reached to your computer, how can the computer know which application the received data belongs to?

This is where the port numbers come in!

In your computer, each application that wants to connect to the internet, it will get a unique number that we call it the port number.

So, a port number basically represents an application! When your computer sends or receives a request over the internet, in the header of that request, there’s a number known as the port.

This number tells the target computer which application the request or response message belongs to! So now, your computer knows to what application it should submit the request or response to.

JavaScript Location port Property

The `port` property is used to set or get the `port` number in the URL of the currently loaded page.

Note: if there’s no port number, the return value will be an empty string.

Location port Property Syntax:

location.port;

Example: window location port

const value = location.port;

console.log(value);
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies