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*/}
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*/}
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:
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.
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.