The following applies to any boolean variable, but I was writing a little function in javascript which reverses the check in a given checkbox, became bored, and wondered how much I could condense it.
Started with:
checkbox = document.getElementById('checkbox');
checkbox.checked = (checkbox.checked ? false : true);
Then moved to
checkbox = document.getElementById('checkbox');
checkbox.checked = !(checkbox.checked);
And then
document.getElementById('checkbox').checked ^= 1;
I couldn't figure out a logical unary approach, like
!(document.getElementById('checkbox').checked);
But I found that -- works, though ++ doesn't (abs val?)
document.getElementById('checkbox').checked--;
I'm also not sure if js (or any language, for that matter) supports some implicit reference to the variable on the left side of the equation, as in:
document.getElementById('checkbox').checked = !(left.side);
There are usually 1000 ways of doing the same thing.. any other neat approaches? Is there a "best" approach for any reason (or most compatible from language to language)?
I always use something like this.checked = !this.checked
for it's the most logical and readable solution I know of. Plus it works in any language I use.