Which of the following is the correct syntax to redirect a URL using JavaScript?

Understanding Redirection in JavaScript

In JavaScript, there are several ways to redirect to a URL, the redirection is typically done using two specific properties: document.location and window.location.

The correct syntax in JavaScript to redirect a URL is either:

  • document.location='http://www.w3docs.com';
  • window.location='http://www.w3docs.com';

How does JavaScript Redirection work?

In JavaScript, both document and window are global objects that provide different functionalities.

The location object is a part of the window object and is accessed through the window.location property. This location object contains information about the current URL and provides methods for dynamic interaction and changes.

The object holds information about the hostname, pathname, protocol, and other URL details. When we use the window.location property, or its equivalent document.location by setting it to a new URL, it loads a new document.

An example would be:


Best Practices

It's considered best practice to use the window.location property for redirecting to a new URL. It is widely accepted and works across all standard-compliant browsers.

The document.location property is also correct, but it is an old property and not part of the latest HTML DOM standards. However, it is maintained for backwards compatibility in most modern browsers.

So, for better compliance and to ensure that your JavaScript will work on different platforms and browsers, it's safer to use window.location.

Syntax like navigator.location='http://www.w3docs.com'; or browser.location='http://www.w3docs.com'; are not valid in JavaScript and will cause runtime errors.

To summarize, redirecting in JavaScript is simple and can be performed using either the window.location or document.location properties, but window.location is the more modern, reliable and accepted practice among developers.

Do you find this helpful?