# Convert booleans to numbers implicitly. (YDKJS Types and Grammar)

Convert booleans to numbers implicitly. (YDKJS Types and Grammar)
0
#1

In YDKJS types and grammar, page 91-92 there are a few code snippets the author listed to show implicit coercion occured in JS.

I don’t really understand the syntax of these snippet as well as how it does what it does.
The original article is here;

1st snippet:

``````function onlyOne(a,b,c) {
return !!((a && !b && !c) ||
(!a && b && !c) || (!a && !b && c));
}

var a = true;
var b = false;

onlyOne( a, b, b );	// true
onlyOne( b, a, b );	// true

onlyOne( a, b, a );	// false
``````

This onlyOne(…) utility should only return true if exactly one of the arguments is true / truthy. It’s using implicit coercion on the truthy checks and explicit coercion on the others, including the final return value.

• How did the author figure out the combination should be : `((a && !b && !c) || (!a && b && !c) || (!a && !b && c))` ?

====================

the 2nd snippet:

``````function onlyOne() {
var sum = 0;
for (var i=0; i < arguments.length; i++) {
// skip falsy values. same as treating
// them as 0's, but avoids NaN's.
if (arguments[i]) {
sum += arguments[i];
}
}
return sum == 1;
}

var a = true;
var b = false;

onlyOne( b, a );		// true
onlyOne( b, a, b, b, b );	// true

onlyOne( b, b );		// false
onlyOne( b, a, b, b, b, a );	// false
``````

What we’re doing here is relying on the 1 for true/truthy coercions, and numerically adding them all up. sum += arguments[i] uses implicit coercion to make that happen. If one and only one value in the arguments list is true, then the numeric sum will be 1, otherwise the sum will not be 1 and thus the desired condition is not met.

• what does `arguments[i]` mean/do?
• how does the onlyOne() function make sure that only returns one when one truthy value is in the arguments?
• the comment on the code said: skips falsy values how did it do it?

Thanks in advance. These snippets got me confused. I know the author is trying to explain implicit/explicit coercion here. But still I want to understand the logic behind these codes.

Also there is a visual tool that can help you understanding JS. If it helps.

0 Likes

#2

Take a look at the arguments object documentation to better understand what it is.

sum starts at 0. The only time sum can increase in value is when a truthy value (i.e. true) is one of the arguments passed into the function. If only one of the arguments is true, then sum will end up 1, so the return sum == 1 will evaluate to true, because 1 == 1. If more than one of the arguments is a true value OR if none of the arguments are true, then sum will be either greater than 1 (the former) or 0 (the latter) and so the comparison sum == 1 will evaluate to false.

This should be clear from the previous answer above.

1 Like