Window.location
Window.location is an object to have information about the actual page. Also you can redirect or upload it.
First of all we need to know window.location properties:
For example, we have this URL: https://sararellano.medium.com/js-shorthands-3f675d4c3b13?filter=fronted#top
* This is a read-only property
PORT
In my example you see the result of the port is ‘’. This is because if the port number is default (80 for http and 443 for https), most browsers will display 0 or nothing.
We are going to see another example to understand port and the difference between host and hostname.
.port => 8080
.host (domain + port) => localhost:8080
.hostname => localhost
.origin (protocol + hostname + port) => http://localhost:8080
WINDOW.LOCATION METHODS
DIFFERENCES BETWEEN .ASSIGN() AND REPLACE()
These methods work very similar: they will redirect you or take you to another url. BUT .assign() will save in history your actual page before the redirection. Therefore, if you use .assign() and click on the back button you can go back to the previous page. And with .replace() you can’t go back.
What have you said?
Maybe I didn’t explain well, so I’m going to add an example:
.assign()
- Open your browser and go to ‘google.com’
- Add window.location.assign(‘https://stackoverflow.com)
- Click “go to back” and you will see ‘google.com’
.replace()
- Open your browser and go to ‘google.com’
- Add window.location.replace(‘https://stackoverflow.com)
- Click “go to back” and you will see a white page
HOW TO REDIRECT A PAGE?
You can do a redirect in 3 ways:
- window.location.href = ‘new web’
- window.location.assign(‘new-web’)
- window.location.replace(‘new-web’)
Only with .replace() you are not going to return to the previous page (.assign() and .href save the previous page in the history).
BONUS
About how to redirect a page, I want to add another method, but not for window.location object. This method is only for window object: .open()
window.open() allows you to open a new tab (a white page) without losing your current page.