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

3
  • 1
    icoop itself is undefined , you need to check first if icoop !== undefined. Commented Feb 3, 2017 at 14:00
  • First you need to have icoop object. Then tryto select it Commented Feb 3, 2017 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. Commented Feb 3, 2017 at 14:14

2 Answers 2

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) || []
});
Sign up to request clarification or add additional context in comments.

Comments

0

Try

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

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

1 Comment

will still throw error when icoop is encountered if there is no such variable declared

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.