1

What is a better/shorter way to write option handling in JavaScript. Instead of the following pattern?

    if(typeof p_options.default_imageset !== "undefined") {
        default_imageset = p_options.default_imageset;
    } else {
        default_imageset = 'mm';
    }

Thanks.

1 Answer 1

8

You can use something like this:

var default_imageset = p_options.default_imageset || 'mm';

If p_options.default_imageset is truthy (not 0, null, false, '', etc.), the operator short-circuits.

Although usually I do it the other way around:

var value = supplied_value || default_value;
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect how do you handle the same case, but 0 being a valid option value. In that case, if you provided 0 it would use the fallback.
@Justin: You'll have to use something like var value = typeof supplied !== 'undefined' ? supplied : default;

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.