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.
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources