Operator NOT (!)

Asked

Viewed 462 times

13

Guys, I’m kind of not knowing how exactly the operator works (!). I always get confused when it comes to using it because I don’t really know how to apply it. It only works with parameters equal to typeof()?

I always use != and I think technically it can replace not... For example:

var tentativas = 0;
var senha = '123';

while(entradasenha != senha){ // como eu poderia usar o (!) aqui?
     if(tentativas > 3) return false;
     var entradasenha = prompt('Digite a senha correta, vc tem 3 tentativas');
     tentativas++;
}

I made this code just to illustrate and know how I could replace the != by the !.

1 answer

18


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:

  • != has TWO things happening in this expression: NOT and EQUAL

  • ! is just the NOT.


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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.