In today's post, I want to talk about a common issue I see in beginners' code. It's not wrong, per se, but it can be made more efficient. Here's a way you can make your code cleaner when returning boolean values.
Let's say I want to create a function that returns true
if a checkbox is checked, and false
if not.
function isChecked(checkbox) {
// Do stuff
}
I can do this using the checked
property (available to any HTMLInputElement of the checkbox
or radio
type). Your first instinct might be to use an if...else
statement like so:
if (checkbox.checked) {
return true;
} else {
return false;
}
This is certainly very readable, but it does more work than is necessary. Let's make it progressively more efficient.
Remove the else
clause
The first thing I could do is remove the else
clause. This works because when you return a value from a function, the function exits immediately and nothing after the return
statement executes.
// If this runs...
if (checkbox.checked) {
return true;
}
// ...then this won't
return false;
Use a ternary
You could even use a ternary operator to make this shorter.
return checkbox.checked ? true : false;
Return the value itself
The thing is, the checked
property just holds a boolean value: true
or false
. This means you can just return the property directly!
return checkbox.checked;
In the same vein, that's why you can just check if (checkbox.checked) {...}
and not if (checkbox.checked === true) {...}
, which would also be unnecessarily long.
So, here's what my function would look like...
function isChecked(checkbox) {
return checkbox.checked;
}
...and I could use it like so:
// Get the first checkbox on the page
const checkbox = document.querySelector('[type="checkbox"]');
if (isChecked(checkbox)) {
// Do something if it's checked
}
As I mentioned at the start of this post, it's not wrong to use the if...else
method. If you're just starting out and you find it more readable, please stick with it! The performance gain is negligible, anyway. This is just a nice little optimization you can make as you become more comfortable with JavaScript. 😊