Search code examples
javascriptconditional-statementsundefinedternary

What is a concise and robust way to write these statements in JavaScript?


I have an <iframe> that uses some variables that are set in an object literal in the parent document. These variables are optional; if they're set, I want to use their values, assigning them to a more succinct global variable; if not, I want to call the function error().

First of all, is this ternary operator statement valid and effective for what I want to do? Are there any potential traps here?

parent.settings.account ? var account = parent.settings.account : error();

Secondly, is there a more concise way to write that statement?

A few of these variables are optional, but if defined, have a range of acceptable values. What's a robust way to handle this? Something like this?

if (parent.settings.polling_interval && parent.settings.polling_interval >= 1000 && parent.settings.polling_interval <= 5000) {
    var polling_interval = parent.settings.polling_interval;
} else {
  var polling_interval = 3000; // default
}

Basically, if it's undefined or out of range, I want to use a default value.

Can I rely on just a conditional statement like:

if (parent.settings.polling_interval) { ... }

or do I need to check if it's undefined, like this?

if (typeof parent.settings.polling_interval !== 'undefined') { ... }

Is there something more robust and/or concise? Thanks for any advice.


Solution

  • This is wrong:

    parent.settings.account ? var account = parent.settings.account : error();
    

    You meant to say:

    var account = parent.settings.account ? parent.settings.account : error();
    

    Or even:

    var account = parent.settings.account || error();