Array Question ? Unexpected outcome, for me

Hi I just started on the array chapter. It said that array’s can contain strings, numbers and booleans.
So I started to mess around a little before moving on to section 2 of the array chapter.

let booleanArray = [true, false, false]
console.log(booleanArray[1] - 1) // logs -1

I though it would log true.
Why does this happen? Thanks in advance.

1 Like

Hey @web3562741697,

So this is a really interesting question! In JavaScript and many other languages, boolean values are actually represented numerically, either 1 or 0.

true === 1;
false === 0;

I’m not 100% sure, but I believe this is due to how computers process information in binary. Ones and zeros.

What you’re telling the console to log is basically, take the second item in my array - remember arrays count from 0 so someArray [1] is the second element. - and subtract one from that item which is the value false in your case.

// it would be the same as saying 
console.log(false - 1) //or
console.log(0 - 1)
 // both of which print -1 

I hope this helps, let me know if you have any other questions.

1 Like

Also here’s a link to a Stack Overflow post which actually does a really great job of explaining this. type conversion - Is true == 1 and false == 0 in JavaScript? - Stack Overflow

1 Like