vendredi 8 février 2019

why should we parse value in switch condition but not in if condition?

function runif() {
  let a = document.getElementById('test').value;
  if (a == 1) {
    console.log("works");
  }
}

function runswitch() {
  let a = document.getElementById('test').value;
  switch (a) {
    case 1:
      console.log("working");
      break;

    default:
      break;
  }
}

function runswitchOne() {
  let a = parseInt(document.getElementById('test').value);
  switch (a) {
    case 1:
      console.log("working");
      break;

    default:
      break;
  }
}
<form action="">
  <input type="text" id="test">
  <input type="button" onclick="runif()" value="click to check if">
  <input type="button" onclick="runswitch()" value="click to check without parseInt">
  <input type="button" onclick="runswitchOne()" value="click to check with parseInt">
</form>

This is the form I have created with a text input and two buttons.

In which the if statement recognize the input and does operation

But in switch I have to make it parse to recognize

I do not understand why it works? I know text input gives sting but if so how if() statement works without parsing?

normally we use if(a == "1") to compare string and not if(a==1)?

but even so it works

Aucun commentaire:

Enregistrer un commentaire