Unexpected result concatenating a boolean with a number

Hi, can anyone explain why in the las console log i have the result “11”? Thanks.

let varBoo = true;

let varString = “String”;

let varNumber = 10;

console.log(varNumber);

console.log(varBoo);

console.log(varNumber + varBoo); Result 11?

Hello @arcrockstar81244, welcome to the forums! Since the integer “representation” of `true` is `1`, when you add `10` and `true`, JS implicitly converts `true` to `1`, and then computes `10+1`, which is `11`.

3 Likes

Excelent, thanks, is there any case wen a programer use a boolean to add 1 or this should be avoided?

1 Like

You can, I’m not sure there’s ever I time where you have to.

What should be avoided is mixed data types in any computation. There will always be clever implementations but this something for demonstration, not production. If we want to add 1, then make it clear that we’re adding 1. For the most part.

Yes, there are instance where adding the result of an evaluation is part of the logic, but that is not something we learn in a tutorial since it will take longer to explain the practicality than spell out the lesson for what it is really worth. Logic cleverness is a worthy study, but more to stretch the mind than build reliable code.

Out of 20 random numbers, how many will be even?

``````let n = 0
for (let x = 2; x < 22; x++) {
n += Math.floor(Math.random() * x) % 2 === 0
}
console.log(n)
``````
1 Like