简体   繁体   中英

Why is this method returning undefined and not boolean?

I have the following method

 const isPrivate = (input) => { return input && input.type && input.type === "private"; } console.log(isPrivate());

Why is it returning undefined and not a boolean?

Logical operators don't coerce or return booleans.

!!input will ensure that input is a truthy value and return a boolean. input.type === "private" will also return a boolean. Since both sides of the operator evaluate to booleans, you'll get the value you're expecting.

 const isPrivate = (input) => { return !!input && input.type === "private"; } console.log(isPrivate()); console.log(isPrivate({})); console.log(isPrivate('')); console.log(isPrivate({ type: 'public' })); console.log(isPrivate({ type: 'private' }));

The forced cast of the evaluation of the existence of input to Boolean is not guaranteed. Test for existence explicitly. This also makes clearer the intent of the evaluation. Additionally, leverage the interpreter to check for errors of intent by reversing order of comparison operands for the === operator. Comparing input.type to literal "private", the interpreter won't let the mistake ["private" = input.type] slide but would be fine with [input.type = "private"]. Finally, there's very little cost for employing parentheses to enhance salience of the delineation of phrases.

const isPrivate = (input) => { return ("undefined" !== typeof input) && ("undefined" !== typeof input.type) && ("private" === input.type); };

There's an issue with your input variable. The error just says that input is undefined, meaning you never gave it a value. Javascript won't try to resolve an undefined value as false, but rather will just throw the error.

If you want to test for undefined first, change it to

return input != null && input && input.type && input.type === "private";

This way it will check if it's null first, and if it's valid, will evaluate as true and move on to the next calculation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM