Operator NOT (!)

12

Folks, I'm kind of wondering how exactly the not (!) operator works. I always get confused when using it because I'm not sure how to apply it. Does it only work with parameters like typeof ()?

I always use the! = and I think technically can replace the 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 exemplify and know how I could replace the! = hair!.

    
asked by anonymous 24.10.2014 / 05:54

1 answer

16

The ! is the not . It returns false to a true value, and true to a false value. In other words, it "inverts" the logical value of an expression.

!= is not equal , that is, "not equal", the same as "other than".

These two lines have the same effect:

while( entradasenha != senha ) {
while( ! ( entradasenha == senha ) ) {


In summary:

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

  • ! is just 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 if as in this last example is if you only need condition 2 (execute something only in case "registered" is false).

    This leaves the code a little smarter in some situations, avoiding an empty% void or a {} with a comparison 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 !
    


Curiosity:

In JavaScript if has the value false and 0 has the value true , more ...
... every nonzero number is considered 1 .

See the effects of true and 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. written as "Booliano" in Portuguese.

    
24.10.2014 / 06:01