Domanda

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.

È stato utile?

Soluzione 2

|| 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;
});

Altri suggerimenti

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;

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.

You should check type

main = function (flag) {
    output({
        flag: (flag===undefined)?true:flag;
    });
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top