0

I am calling two functions and checking if the given input has barcode and qr code

var decode = jsQR.decodeQRFromImage(rawImageData.data, rawImageData.width, rawImageData.height);
checkBarCode(function(err, result) {
    if (result) {
        Result.pages.push({
            ValidTicket: decode ? true : false //here i want to assign true or false if barcode or qr code is present.
        });
    }
});

is this correct?

ValidTicket: decode  || result ? true : false
1
  • Seems correct to me Commented Mar 26, 2017 at 11:49

2 Answers 2

1

Your assignment does work correctly, but I might suggest using two boolean NOT operators instead, which is slightly terser:

var decode = jsQR.decodeQRFromImage(
  rawImageData.data,
  rawImageData.width,
  rawImageData.height
);

checkBarCode(function(err, result) {
    if (result) {
        Result.pages.push({
            ValidTicket: !!(decode || result)
        });
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1

Yes, that's correct. If either decode or result is truthy*, you'll assign true; if both are falsy*, you'll assign false.

You may get someone telling you to just do this:

ValidTicket: decode || result

...but that won't necessarily assign either true or false, because of JavaScript's curiously-powerful || operator (that's a post on my anemic little blog); instead, it'll assign the value of decode if it's truthy, and the value of result if not. So if you really need true or false, you need to use the conditional as you have done.


* About "truthy" and "falsy":

"truthy" - a value that coerces to true when used as a boolean

"falsy" - a value that coerces to false when used as a boolean

The falsy values are 0, "", NaN, null, undefined, and (of course), false. All other values are truthy.

Comments

Your Answer

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