What is a concise and robust way to write these statements in JavaScript?
-
19-09-2019 - |
Question
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();
OTHER TIPS
var account = parent.settings.account;
if (!account)
error();
if ((p = parent.settings.polling_interval) && p >= 1000 && p <= 5000) {
...
}
var polling_interval = (p = parent.settings.polling_interval) && p >= 1000 && p <= 5000 ? p : 3000;
[1]
parent.settings.account ? ( var account = parent.settings.account ) : error();
This will raise a SyntaxError since you can't define a variable in that manner.
If error()
raises an Exception / throws an Error then you can do:
if ( !parent.settings.account ) {
error()
}
// continue code
As previously stated you can also assign the variable to the property:
var account = parent.settings.account || error();
[2]
var pollingInterval = parent.settings.polling_interval &&
parent.settings.polling_interval >= 1000 &&
parent.settings.polling_interval <= 5000 ?
parent.settings.polling_interval : 3000;
[3] You can use if ( parent.foo )
and if foo
is undefined no strict error will be thrown but it will just equal undefined, assuming parent is always defined.
If settings is defined and polling_interval is not, same case. If you're sure the property is set and the settings object will exist, then you can use
if ( parent.settings.polling_interval ) { }
It would help stating what error()
actually does.