1

I am using ternary expression to check if the variable exists to display value accordingly, but since, I need to check both if it exists and that is has some values in it, it fails on checking the condition when the variable is undefined. How can I fix that?

This is the code:

$('#select').selectize({
    items: typeof icoop != "undefined" && icoop != null ||  icoop.selectedUsers.length < 1 ? icoop.selectedUsers : []
});

I get:

Uncaught ReferenceError: icoop is not defined

Leff
  • 1,968
  • 24
  • 97
  • 201
  • 1
    icoop itself is undefined , you need to check first if icoop !== undefined. – Deep Feb 03 '17 at 14:00
  • First you need to have icoop object. Then tryto select it –  Feb 03 '17 at 14:02
  • For clarity, the reasoning behind the logic is correct but not the expression of that reasoning. What happens is that `typeof icoop != "undefined"` is **false**, which makes the entire AND condition also **false** but then you are left with, essentially, `false || ( icoop.selectedUsers.length < 1 ? icoop.selectedUsers : [] )` and because this is an OR, the evaluation will continue on the right, where the error occurs. – VLAZ Feb 03 '17 at 14:14

2 Answers2

5

icoop is undefined, so accessing any property or function will fail.

Check for icoop before checking for icoop.selectedUsers:

$('#select').selectize({
     items: (typeof icoop !== 'undefined' && icoop && icoop.selectedUsers && icoop.selectedUsers.length > 0) ? icoop.selectedUsers : []
});

You may also clean up the code a little bit:

// Check for icoop existence. Assign a default value if it is undefined or null.
var icoop = (typeof icoop !== 'undefined' && icoop) || {};

$('#select').selectize({
     items: (Array.isArray(icoop.selectedUsers) && icoop.selectedUsers) || []
});
Matias Cicero
  • 25,439
  • 13
  • 82
  • 154
0

Try

items: icoop != undefined && typeof icoop.selectedUsers != "undefined" &&...

also check out How to check for "undefined" in JavaScript?

Community
  • 1
  • 1
Tobias G
  • 583
  • 2
  • 10