Skip to content

Latest commit

Β 

History

History
45 lines (33 loc) Β· 1.64 KB

File metadata and controls

45 lines (33 loc) Β· 1.64 KB

prefer-location-assign

πŸ“ 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.

Examples

// ❌ - 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');
}