Search code examples
javascriptfunctiondefault-value

Assigning a default value through the logical operator OR


We know that the javascript logical operator || produces the value of its first operand if the first operand is true. Otherwise, it produces the value of the second operand.

So in this example:

<script language="javascript">
function test (value){
    this.value = value || "(value not given)";
}
</script>

if the parameter value passed to the function is treated as false like the integer 0 or the empty string "" then this.value will be set to (value not given) which is not true correct (because indeed we are passing a value).

So the question is which should be the best way to set this.value?

EDIT: All 4 first answers use the ternary operator "?". My question is about "||" operator.


Solution

  • The scheme with || is the most convenient to write, but it can ONLY be used when a falsey value (undefined, null, 0, "", false, NaN) is not a legitimate value. (When you just want to deal with null and undefined, you can use the new nullish coalescing operator (??) described in this proposal and included in ES2020.)

    If you want to allow specific falsey values and not allow others, then you have to write more specific code to handle your specific cases. For example, if you wanted to allow an empty string, but not allow null or undefined or other falsey values, then you'd have to write more specific code like this:

    function test(value) {
        if (value || value === "") {
            this.value = value;
        } else {
            this.value = "(value not given)";
        }
    }
    

    Or if you only want to exclude only undefined, you can test for it specifically:

    function test(value) {
        if (value === undefined) {
            value = "(value not given)";
        }
        this.value = value;
    }