How does the Boolean value return in this JavaScript?

I am new to programming and work hard to teach myself. I came across the following problem on the Internet and tried to solve it, but was stuck:

"Write a function that takes three arguments and returns true if only one of these arguments is true and false if not. Do not use the && or || or if statements.

This stopped me for the last two days, so I moved on to the solution, and I had trouble figuring out:

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

I understand the syntax, but I do not understand the logic or why it works. Can anyone help me? I want to find out why the code works, and not just remember the syntax.

+4
source share
2 answers

!! . , JavaScript , false 0 true 1.

, (!!x + !!y + !!z === 1) x, y z true false, . 1 , 1, === 1 true, false.

, , :

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

!! "" , 0 1 +. , 1 , .

+1

Source: https://habr.com/ru/post/1686512/


All Articles