1

Here is an example where I use the || operator to assign a default value if the argument is undefined.

output = function (data) {
    console.log("data.flag =", data.flag);
}

main = function (flag) {
    output({
        flag: flag || true;
    });
}

main(true);  // data.flag = true 
main(false); // data.flag = true 

However, the operation is ignored so always that the default value is assigned. How can I fix this? Here on JSFiddle - you have to open the console to see the output.

1
  • flag || true will always be equal to true if flag is boolean. Commented Feb 7, 2014 at 15:04

4 Answers 4

2

When you pass in false you have this

flag: false || true;

And if you know how || works, if the left side is falsey, it will take the right hand side.

You need to check for undefined since false is FALSE

flag: flag!==undefined ? flag : true;

Other option would be check argument length

flag: arguments.length ? flag : true;
Sign up to request clarification or add additional context in comments.

Comments

1

|| is not an 'assign if undefined operator', although its semantics allow it to be used in a way that makes it seem like that's what it does. It's the OR operator. It evaluates the right side if and only if the left side is 'falsey'—that is, when converted to a Boolean value, it is false. From MDN:

Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false.

Try using a more explicit test:

output({
    flag: (typeof flag === "undefined") ? true : flag;
});

1 Comment

Do you know if there is a wrapper function for (typeof flag === "undefined") ? true : flag; in a common library such as Underscore.js
1

You should do something like this:

flag: typeof flag === 'undefined' ? true : !!flag;

|| is not good for what you want to use it. It will return the result of the first operand if it is truthy, and return the second otherwise. For example false || true returns true.

My example will return true if flag is undefined, and will return flag casted to boolean (so either true or false) otherwise - so you end up with a clean flag, no tricks :).

One more tip: don't use tricks that you do not understand :). They will lead to strange bugs.

Comments

0

You should check type

main = function (flag) {
    output({
        flag: (flag===undefined)?true:flag;
    });
}

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.