Skip to content
Advertisement

JS ECMA6 – Ternary Operator for backwards compatibility

I have a piece of javascript code that uses the ECMA6 dataset property to access an objects data-foo attribute of an element e. Unfortunately, this is not compatable with <=IE10. To combat this, I’ve rewritten my code to using a ternary operator, using dataset when supported and getAttribute when not:

(e.dataset) ? e.dataset.foo : e.getAttribute('data-foo');

But why shouldn’t I just replace the entire line with e.getAttribute('data-foo')? What is the real benefit of using ECMA6 standards when previous standards are just as good and more widely supported?

Advertisement

Answer

First of all, dataset property doesn’t seem to be part of ES6 spec. It is part of HTML spec.

Coming to your question,

What is the real benefit of using ECMA6 standards when previous standards are just as good and more widely supported?

Simplicity.

As you may observe, among the two approaches, e.dataset.foo and e.getAttribute('data-foo'), the former is less verbose, and hence desirable in many cases. For one, it reduces the size of Javascript files you ship.

The spec even highlights the point:

The dataset IDL attribute provides convenient accessors for all the data-* attributes on an element. …

[Emphasis mine]

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement