Last Updated: August 02, 2019
· aleclanter

IE 8 Ternary Operator Oddness

Just ran across this at a client site where they're using older browsers.

We have a block of JavaScript that needs to fetch the text of an element. Since "innerText" doesn't work on Firefox, we have a statement like this:

var someValue = $.browser.mozilla ? element.textContent.toLowerCase() : element.innerText.toLowerCase();

In Chrome, Firefox, Safari and IE 9+, all works as expected. IE 8, however, gives the error that toLowerCase() is not defined.

The solution?

var someValue;
if ($.browser.mozilla) {
    someValue = element.textContent.toLowerCase();
} else {
    someValue = element.innerText.toLowerCase();

IE 8 apparently tries to parse both sides of the ternary before evaluating the truth of the conditional, causing this lovely little gotcha.

2 Responses
Add your response

  1. parse != execute. I believe all sane intepreters parse both expressions before executing anything.
  2. a real proof would be to run var someValue = false ? alert("A") : alert("B"); If you will see both alerts, then surely something's wrong. Also if you see "A", then something's wrong.
  3. in your particular case I would start from a suspicion that $.browser.mozilla is true, and first try to check if I am right by replacing $.browser.mozilla with false. If problem persists, then I would go to ...
  4. check if the source of the problem lays in the splitting of the expression into two separate lines. Maybe it is just a formatting of the arcticle, but if in the real code you also have a newline, then it is possible that it is interpreted as the end of a statement. If that also doesn't help, then I woudl go with ...
  5. reading the error message again. Is it about calling a method on a non-object, or is it about missing method? First option means that element.innerText or element.textContent is missing, while the other means that the method toLowerCase() is missing. The later might mean that the field exists but is not a string.

I would like to see the real original code, could you paste it?

over 1 year ago ·

Why not

over 1 year ago ·