The !
is the not. It returns false to a true value, and true to a false value. In other words, it "reverses" the logical value of an expression.
!=
is not Equal, that is, "not equal", the same as "different from".
These two lines have the same effect:
while( entradasenha != senha ) {
while( ! ( entradasenha == senha ) ) {
In short:
Other examples of equivalent conditions:
if( ! ( x > 3 ) )
is the same as if( x <= 3 )
These two lines have the same effect:
if ( !cadastrado ) { operacao 1 } else { operacao 2 }
if ( cadastrado ) { operacao 2 } else { operacao 1 }
One of the advantages of !
in a if
as in this last example is if you only need condition 2 (perform something just in case "registered" is false).
This makes the code a little more elegant in some situations, avoiding a {}
empty or a if
compared to Boolean 1:
if (cadastrado) {} else {return "usuário não cadastrado"}; // sem o !
if (cadastrado == false) return "usuário não cadastrado" ; // sem o !
if (!cadastrado) return "usuário não cadastrado"; // usando !
Of curiosity:
Javascript false
has the value 0
and true
has the value 1
, but...
... any number other than zero is considered true
.
Look at the effects of !
and of Boolean in these cases:
VALOR RESULTA EM
!0 true
!1 false
!2 false
true + true 2
!0 + 2 3
!1 + 2 2
!7 + 2 2
!true false
!false true
3 > 2 true
! ( 3 > 2 ) false
! ( ! 0 ) false
! ( ! ( ! 0 ) ) true
1. spelled as "boolean" (see about Açoriano on the same page) and listed as "boolean" in Portuguese.