4

I'm pretty new to programming and have been working hard to teach myself. I came across the following problem online and tried to solve it, but hit a dead end:

"Write a function that accepts three arguments and returns true if only one of those arguments is truthy, and false if not. Do not use && or || operators or if statements."

This stumped me for the past two days, so I moved on to the solution, which I'm having trouble figuring out:

function onlyOne(x, y, z) {
    return (!!x + !!y + !!z === 1);
}

I understand the syntax, but I don't understand the logic or why this works. Would someone be able to help me out? I want to learn why the code works, and not just memorize syntax.

4
  • 2
    The addition operator treats the boolean values as integers, 0 for false, 1 for true. !! is a way to convert just about any value to its boolean equivalent Commented Sep 28, 2017 at 0:13
  • FYI, this sort of boolean comparison is called an "exclusive OR" or XOR if you're interested in doing some more research. Commented Sep 28, 2017 at 0:19
  • !! = "bang bang you're a Boolean" Commented Sep 28, 2017 at 4:00
  • It might be worth pointing out that !! isn't a special operator but just two repeated !. The first one converts the argument to a Boolean and inverts the result, and the second one inverts it again to arrive back at the original object's truthiness value. Commented Nov 14, 2017 at 19:46

2 Answers 2

4

!! casts the value to an actual boolean. When you perform addition on boolean values, JavaScript coerces them into number, false being 0 and true being 1.

Basically, (!!x + !!y + !!z === 1) casts x, y, and z to true or false, then adds them all together. If only 1 of them is truthy, the value will be 1, and === 1 will be true, else it will be false.

Here is an example showing how addition with booleans works:

console.log(false + false); // 0
console.log(false + true);  // 1
console.log(true + true);   // 2

Sign up to request clarification or add additional context in comments.

Comments

1

!! "casts" your variable into a boolean which can only has the value 0 or 1 when casted back into a number via the + operator. If you think about it, you can only get 1 after adding them together if only one variable is true.

1 Comment

"which can only has the value 0 or 1" <- this isn't quite accurate. The boolean primitives true and false are type-cast to integers 1 and 0 by using them in a mathematical expression

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.