Is the putting a classList method inside square brackets considered as good practice? I mean, sometimes I prefer to do:
elem.classList[ifTrue ? 'add' : 'remove']('className');
as opposed to:
if (ifTrue) {
elem.classList.add('className');
} else {
elem.classList.remove('className');
}
Also, does using brackets have any impact on the performance/speed of code execution?
Is the putting a classList method inside square brackets considered as good practice?
There's nothing really wrong with it. It's shorter, more concise, no code duplication. As you say, you sometimes prefer it - if you know when to use and when not, then it's fine. The factors are:
ifTrue
, then I'd choose if-else. On the other hand, the repetion of elem.classlist
and 'classname'
are not optimal either. There is a completely different and much better third way though: Using the toggle
method of classlists . It does take a second parameter which does just what you want to do:
elem.classList.toggle('className', ifTrue);
It was just invented for this very common case! Admittedly, it's worse for readability as many developers don't know what toggle
does.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.