简体   繁体   中英

Using classList method in square brackets

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:

  • readability . Much opinion-based. I like it, others don't. Know your audience, I wouldn't suggest this for newbies.
  • maintainability . When it's likely that other things need to be done depending on ifTrue , then I'd choose if-else. On the other hand, the repetion of elem.classlist and 'classname' are not optimal either.
  • performance . The second is more likely to be optimised (because static method names), that's true. But there hardly is measurable impact on your execution speed, as the most significant work is done in the DOM. You're not using this piece of code in a performance-critical section anyway. (Do you? Then benchmark).

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM