What does if (variable) {/ * action * /} mean?

1

By putting only the variable within if , for example

if( variavél ){ /*ação*/}

What does this if mean?

And contrary

if( !variavél ){ /*ação*/}

    
asked by anonymous 27.01.2018 / 23:42

2 answers

10

Comparison structures like if expect Boolean values (TRUE, FALSE). But with the evolution of languages the concept of what is true or false has been expanded. so let's give an example

var teste = false;
if(teste == true){
  alert('Sou verdadeiro');
}
else{
  alert('Sou falso');
}

We can see that clearly the variable teste is false, porting will print sou falso .

But we can hide the value to be compared, since the teste variable is already a Boolean value. Porting the code would work even written this way:

var teste = false;
if(teste){
  alert('Sou verdadeiro');
}
else{
  alert('Sou falso');
}

That said, we can verify that Javascript (and several other languages) consider as false the following cases:

  • Indefinite value
  • Null
  • Boolean false
  • Number zero (0)
  • String of zero length (empty string)
  • Anything other than these examples is considered true, so if I make the following code

    var teste = 12;
    if(teste){
      alert('Sou Verdadeiro');
    }
    else{
      alert('Sou Falso');
    }

    The variable teste is considered true because it was started with a value other than zero.

    Now for the ! operator that comes before a comparison within if , it simply reverses the comparison value. If we compare a value that is true, it reverses to false.

        
    28.01.2018 / 00:00
    2

    The answer from Phelipe is correct, this is the shorthand , where:

    if(variavel) returns true in cases where the variable variavel :

    • is not null (has some value)

    • is different from 0 (number, not string).

    • is different from empty ( space is not empty)

    • is true ( variavel = true; )

    In case of (!variavel) returns false where variavel :

    • is null (has no set value)

    • is empty ( variavel = ""; )

    • is false ( variavel = false; )

    • is equal to 0 (number, not string)

    In this link you can learn other short writing techniques some JavaScript codes.

        
    28.01.2018 / 01:02