I'm not able to do a condition with if for example:
asd=true;
if(asd=='true'){
alert('funcionou');
}
but it seems that somehow it is not entering if
I'm not able to do a condition with if for example:
asd=true;
if(asd=='true'){
alert('funcionou');
}
but it seems that somehow it is not entering if
Asd is a Boolean value and can not be treated as a string try the following:
var asd=true;
if(asd==true){
alert('funcionou');
}
or
var asd=true;
if(asd){
alert('funcionou');
}
As you have already replied, I'll just give you a tip.
Some conventions (eg PHPCS, pear package) do not even allow comparisons using double equal (==), but require triple (===). Why?
Comparing equality with == may be unpredictable:
asd == true // true
asd == 1 // true
asd == 'true' // false
But with === we have accurate results:
console.log(asd === true); // true
console.log(asd !== false); // true
console.log(asd === 1); // false
console.log(asd === false); // false
If you assign true
to a variable, then the expected minimum would be that compared to the same original value, the condition passed ... but you used something different in the comparison: 'true'
.
In javascript, 'true'
is not the same as true
. The first is a string, that is, it is a text, in which the word true is written, the second is a Boolean value, meaning true .
Conclusion: When comparing be sure that the type of objects being compared is compatible. If they are not, then possibly the comparison will fail.
You are comparing two different types of variables.
Although not a strict comparison, it will fail because they are not the same.
==
normal comparison, eg 1 == true // verdadeiro
===
strict comparison, check if the type is the same, eg 1 == true // falso
The simplest way for you to compare in javascript is something true, assuming it is not fake. Example:
var foo = true;
var bar = false;
if (foo) { /* vai executar pois foo existe e é alguma coisa */ }
if (bar) { /* não vai executar, pois bar é falso */}
You can test if something is not false using !variavel
, this will invert the value of the variable, first javascript will convert the variable to a testable (boolean) value, then reverse the value of the result and then apply the conditional.
Values converted to false
:
false
0
-0
''
null
undefined
NaN
Values other than these will be converted to true
.
When you want to ensure that a variable is exactly a false or true value you should make a strict comparison:
var verdadeiro = true;
if (verdadeiro === true) { /* faça algo */ }
It is still possible to restrict the variable to a specific value, for example:
var foo = verdadeiro === true;
That is, if the true variable is anything other than true
, foo
will be false
, even if it is an object or things that can be converted.