Starting this series of posts on small examples where refactoring the code can make it bugfree and more robust. Here is part 1. Enjoy!
document.querySelector('input').addEventListener('input', e => {
if (e.target.value.indexOf('>') === 0) {
isCommandMode = true;
}
}
I expect that when somebody types in >
as the first character in the input, isCommandMode
should be set to true
. But also if that condition isn't met, it should become false
You may say we can just add the missing else condition, like so:
document.querySelector('input').addEventListener('input', e => {
if (e.target.value.indexOf('>') === 0) {
isCommandMode = true;
}
else {
isCommandMode = false;
}
}
That solves the purpose, but we can write this in a much better way which will make the code more concise, readable and also it would have prevented our bug in the first place:
document.querySelector('input').addEventListener('input', e => {
isCommandMode = e.target.value.indexOf('>') === 0;
}
That one line now handles both conditions itself. Sweet, ain't it? Hope you had fun going through this refactor. Until, next time.
You can also follow me on twitter to know about such future posts.
Top comments (2)
Great find! This is one improvement everyone can apply very quickly to their code without any side effects (usually).
p.s: you can postfix the triple graves with javascript to get keyword highlighting in your code paragraphs
Ahh. missed them. Added now. Thanks :)