Why the Boolean value of undefined is false, but when
compare with false da they are different?
Touching the boolean data topic we know that its logical representation is as follows:
True that in binary representation is equal to 1
False that in binary representation is equal to 0
So it is clear that the Boolean data type has a predefined structure and a specific value assigned by default in javascript
What happens with undefined?
It is a data type as well ( special primitive ), however, has no value assigned by default in the language. It is used to specify or reserve a memory space to which no value has been assigned.
That's why
console.log(undefined == false)
does not return true
False can be taken as 0
, however, it is not so with undefined because it does not have numerical representation in terms of assigned value, hence the fact that make it a special primitive because it generates certain exceptions in the standard behavior of the language. I could declare a variable:
var x;
Even though there is x
, it has a reserved space in memory and could do operations with it later ... what happens with the previous instruction is that it reserves the space in memory for x
but it is not defined (it is undefined), that is, it does not have logical representation and that is why:
console.log(x == false)
will also not throw true
Of course, the conversion of javascript types handles this type of exception if you make a strict comparison of logical type:
console.log(Boolean(undefined) == false)
if it will throw true
It will throw true because you are forcing undefined to take a logical or boolean value and the default behavior when declaring it a boolean will always be false unless you indicate that it is not.
For more information you can visit: undefined-javacript you can also read < a href="https://fernetjs.com/2011/12/null-vs-undefined/"> null vs undefined
Why if the equality operator tries to convert the types, with
undefined does not the same thing happen?
Precisely because the goal of undefined is to declare a variable (for example) without necessarily knowing what its type is. That is why javascript handles this kind of exception to its indirect type conversion rule.
Different is to compare the boolean of undefined with false:
console.log(Boolean(undefined) == false)
With the previous instruction you are forcing an automatic type conversion directly so javascript by default "assigns" the value of false in the conversion and false==false
as result is true . p>
I hope it helps. Greetings!