Albert Rothman Albert Rothman - 1 month ago 9
Javascript Question

Why doesn't ternary operator work with undefined as falsy in javascript?

I looked around and didn't find anyone asking this question, which I find somewhat surprising. Maybe I'm just missing something here, but I have the following code:

return $type_cnts ? JSON.parse($type_cnts)[premType] : 0;

which to my throws

Uncaught ReferenceError: $type_cnts is not defined

Shouldn't the fact that
is undefined make it false and thus make the ternary operator return zero?

Answer Source

No, undeclared variables throw ReferenceErrors when you try to access them. However, if you declare the variable with no value,

var $type_cnts;

then you're ternary operator will work:

$type_cnts ? JSON.parse($type_cnts)[premType] : 0; // 0

Additionally, undefined properties of objects do not throw errors when you try to access them (common knowledge). And this applies to the window object, so if you change your code to

window.$type_cnts ? JSON.parse($type_cnts)[premType] : 0;  // no error

and even not declare $type_cnts, then your code will not throw an error.