I wrote this simple function once, to display notifications on hash change :
function watchHash() {
if(location.hash == '#thanks') {
displayNotification('Thanks for your feedback, I\'ll try to get back to you as soon as possible.'); // Notify on form submit success
}
if(location.hash == '#error') {
displayNotification('Oops, something went wrong ! Please try again.'); // Notify on form submit error
}
}
window.onhashchange = watchHash;
I came back to it today and I thought, is it correct if I write it this way instead?
function watchHash() {
if(location.hash == '#thanks') {
displayNotification('Thanks for your feedback, I\'ll try to get back to you as soon as possible.'); // Notify on form submit success
}
else if(location.hash == '#error') {
displayNotification('Oops, something went wrong ! Please try again.'); // Notify on form submit error
}
else {
return;
}
}
window.onhashchange = watchHash;
If so, is it relevant?
I’m a bit confused here, I’d like to stick to best practices.
Thanks for your help.
The second scenario is much better. Why?
Because in the first scenario if first condition is met or not met – it doesn’t matter, the second case is checked too, the third, the fourth and so on.
In second case If the first case fails, then the second one is tested, if it fails, the third is tested, so your software does not spend useless time checking scenario which will not happen.