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.
0forfalse,1fortrue.!!is a way to convert just about any value to its boolean equivalentXORif you're interested in doing some more research.!!= "bang bang you're a Boolean"!!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.