What is window.location.assign() in Javascript?

The window.location.assign() method belongs to the Location object. It allows the window to load a document specified by the provided URLUniform Resource Locator. Once you have navigated from the current window to the new one, you can still go back to the former by pressing the back button.

Syntax

location.assign(url)

// OR
window.location.assign(url)

Parameter

url: this is the URLUniform Resource Locator that will be navigated to.

Code

Example 1

  • Let’s use the window.location.assign() to navigate to "https://educative.io/answers".

  • In the example below, we create a navigate() function that will call the window.locaton.assign().

  • An onclick event listener is added to the button to call this function when it is clicked.

Note: An incorrect URL will throw a DOMException error.

Example 2

  • In the example below, we will use an invalid URL, "hps://educative.io/edpresso".
  • This will cause an error to occur and there will be no navigation.