What does if(variavél){ /*action*/}mean?

Asked

Viewed 765 times

1

When placing only to variable within the if, for example

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

What does that mean if?

And to the contrary

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

2 answers

10


Comparison structures like the if expect boolean values (TRUE, FALSE). But with the evolution of languages the concept of what is true or false has been broadened. so let’s take 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 so will print sou falso.

But we can hide the value to be compared, since the variable teste is already a boolean value. Porting the code would even work written that 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:

  1. undefined value
  2. Null
  3. Boolean false
  4. Zero number (0)
  5. String of zero length (Empty string)

Anything other than these examples is considered true, so if I do 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 non-zero value.

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

  • Addendum: You can also use the tabela verdade to study how the conditional structure works if..else.

2

The response of Phelipe is correct, it is the technique of 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 the case of (!variavel) returns false where the variavel:

  • is null (has no defined value)

  • is empty (variavel = "";)

  • is false (variavel = false;)

  • is equal to 0 (number, not string)

At this link you can learn other techniques of short writing some Javascript codes.

Browser other questions tagged

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