0

I would like to know if this is the best way to approach this javascript problem. I would like to first detect if a variable is undefined. If it is not, I would like to insert a default value.

Example, This if statement is receiving a variable called zoomControl. It can have 3 possible values. true, false, or undefined.

I would like the output to be: true = true, false = false, undefined = true

if (opt.set_zoomControl) {
            set_zoomControl = opt.set_zoomControl
    } else {
        set_zoomControl = true;
    }

Is this efficient? Can this be shorted or rewritten?

thank you.

1

4 Answers 4

1
set_zoomControl = ( opt.set_zoomControl === false )? false: true;
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I forgot a key requirement in my question description. The default value (undefined value) is not always true. (As in the example code). The default value maybe sometimes be false. This works for both occurrences.
0
if (opt.set_zoomControl) {
            //true
}
else{
       //false or undefinded
}

Comments

0

Here is the most concise way to write this:

set_zoomControl = opt.set_zoomControl !== false;

It shouldn't be too difficult to see that this works for all three of your cases:

false !== false      // evaluates to false
true !== false       // evaluates to true
undefined !== false  // evaluates to true

Your current method will result in set_zoomControl always being true. If you wanted to use your if/else format for clarity it will be most straightforward to handle the false case first and then let true and undefined be handled by the else:

if (opt.set_zoomControl === false) {
    set_zoomControl = false;
} else {
    set_zoomControl = true;
} 

Comments

0

set_zoomControl = opt.set_zoomControl || 0;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.