Angularjs conferring variable on a conditional can give problem without specifying?

Asked

Viewed 12 times

0

Symbolic example:

var num = undefined; // resultado será 3
var num = null; // resultado será 3
var num = 1; // resultado será 2
var num = 0; // resultado será 3

if (num) {
   resultado = 2;
} else {
   resultado = 3;
}

But many times in the code I observe that if appear 1 or 0 may influence the answer we are waiting..

  • If my answer helped you to understand the subject put as a response accepted. If you need any further explanation comment on the answer.

1 answer

0

I will follow your example:

var num = undefined; // resultado será 3
var num = null; // resultado será 3
var num = 1; // resultado será 2
var num = 0; // resultado será 3

if (num) {
   resultado = 2;
} else {
   resultado = 3;
}

In Javascript the values null, undefined, 0, '', "" and NaN are considered as false.

All other values are considered as true.

In your case, if num for undefined, null or 0 the code inside the block if will not be executed and therefore the code resultado = 3;block else will be executed.

In the case of num was 1 the result value will be 2 'cause it goes inside the block if and the code resultado = 2; is executed.

I also leave here a small quick example to run and check for yourself:

var valores = [undefined, null, 0, NaN, '', "", 1, 2, "0", [], "false", {}];

valores.forEach((valor) => {
  if(!valor){
    console.log("Quando o valor é `" + valor + "` corresponde a false");
  }
  else{
    console.log("Quando o valor é `" + valor + "` corresponde a true");
  }
  
})

Browser other questions tagged

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