window.location.href or window.open()

Photo by Richy Great on Unsplash

window.location.href or window.open()

Navigating in the browser with the window object

ยท

2 min read

When we have to navigate the window or the current page to another URL with javascript, window.location.href and window.open() are two common options to choose from. The question is, which one of these options should be preferred? Is there any difference? Does the browser execute/behave differently for both of them?

window.location.href

window.location has properties that describe the current location of the window. Changing the href value triggers the window to reload to the new href.

window.open

window.open API has all the specific options for navigating a window.

I looked up the web and the only popular answer that can be found everywhere is that window.location.href is not a method and window.open will open a new tab. Which is not a huge surprise if you've already been working with URLs. ๐Ÿคทโ€โ™‚๏ธ Screenshot 2022-11-16 at 9.47.35 PM.png

I asked this on Twitter and here's the responses I got ๐Ÿฅ...

href is a property for window.location object, we can either retrieve current page URL or update it with new one.
However, window.open is a method for window object to load resources ONLY. Life becomes easier with this feature n its params when u want to load URL๐Ÿ˜‡

โ€” Apoorva CG (@ApoorvaCg) November 5, 2022
also, Jake (@jaffathecake) replied with the most popular line about window.open on the internet

window.open opens a new window/tab

โ€” Jake Archibald (@jaffathecake) November 5, 2022

I also dug up many other places on the internet but the answers found were not different from the ones given above.

After having this post in draft for weeks, I decided to publish it anyway with what I could found in the process of researching it.
If you have some interesting facts to share about this, make sure to write it down in the comments.

Conclusion

The main difference between navigating using window.location.href vs window.open are:

  1. window.open opens a new tab with the URL
  2. window.open method provides various options for navigating
  3. window.location.href is a property of the current window location

If you want to learn more about these APIs, checkout the linked resources!

Thanks for reading!

ย