π Prefer location.assign() over assigning to location.href.
πΌπ« This rule is enabled in the β
recommended config. This rule is disabled in the βοΈ unopinionated config.
π§ This rule is automatically fixable by the --fix CLI option.
Location#assign() is more explicit and semantic than assigning to .href. Use assign() when you want to preserve the current page in browser history (user can go back), and Location#replace() when you want to replace the current history entry.
// β - Assigns to a property (less semantic)
location.href = url;
// β
- Method call is more explicit
location.assign(url);// β
- Normal navigation, user can go back
const loginUrl = 'https://example.com/login';
location.assign(loginUrl);// β
- Use replace() for redirects where user shouldn't go back
if (isLoggedOut) {
location.replace('/login'); // Can't go back to protected page
}// β
- assign() for user-initiated navigation
button.onclick = () => location.assign('/next-page');
// β
- replace() for authentication redirects
if (!hasValidToken) {
location.replace('/login');
}