Prozrachniy Prozrachniy -3 years ago 164
Javascript Question

ternary operator causes an error inside if statement

Why is this statement causing 'TypeError: Cannot read property 'toString' of undefined' ? I thought it'd notice that

is undefined and just avoid the line where it tries to make a string out of
If I remove
true ||
from 'if' statement it works fine

let und = undefined;

if (true || und ? und.toString() === 'anything' : false) {
// do something


Answer Source

This instruction:

true || und ? und.toString() === 'anything' : false

Will be read as:

(true || und) ? und.toString() === 'anything' : false

Since the OR statement is true, und.toString() === 'anything' will be executed, even if und is undefined.

You need to put parentheses around the ternary operator.

let und = undefined;

if (true || (und ? und.toString() === 'anything' : false)) {
  console.log('Yeah, no error thrown');

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download