Error javascript if

Asked

Viewed 182 times

4

I’m not able to make a condition with if for example:

asd=true;
if(asd=='true'){
   alert('funcionou');
}

but it seems that somehow it is not getting into the if

4 answers

7


Asd is a value boleanus and cannot be treated as a string try the following:

var asd=true;
if(asd==true){
   alert('funcionou');
}

or

var asd=true;
if(asd){
   alert('funcionou');
}

5

Since you already answered, I’ll just give you a hint.

Some conventions (e.g. PHPCS, Pear package) do not even allow comparisons using double equal (==), but require triple (===). Why?

Comparing equality with == can 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

2

If you assign true a variable, so the expected minimum would be that compared to the same original value, the condition would pass... 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, a text, in which the word is written true, the second is a boolean value, meaning true.

Completion: when comparing make sure that the type of objects being compared is compatible. If they are not, then possibly the comparison will fail.

1

You’re comparing two different types of variables.

Even though it is not a strict comparison, it will fail because they are not equal.

  • == normal comparison, ex: 1 == true // verdadeiro
  • === strict comparison, checks if the type is the same, ex: 1 == true // falso

The simplest way for you to compare something in javascript is true, assuming it is not false. 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 fake using !variavel, this will invert the value of the variable, first javascript will convert the variable to a testable value (boleano), then it will invert the value of the result and then apply the conditional.

Values converted to false:

  • false
  • 0
  • -0
  • ''
  • null
  • undefined
  • NaN

Different values from these will be converted to true.

When you want to ensure that a variable is exactly a false or true value you should make strict comparison:

var verdadeiro = true;
if (verdadeiro === true) { /* faça algo */ }

It is still possible to restrict that the variable is a specific value, for example:

var foo = verdadeiro === true;

That is, if the true variable is anything other than true, the foo will be false, even if it is an object or things that can be converted.

Browser other questions tagged

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