I’m trying to convert an if statement into a switch statement using javascript. This is the working if statement:
if(!error1(num, a_id) && !error2(num, b_id) && !error3(num, c_id) && !error4(num, d_id)) {
a.innerHTML = num;
Any tips on how to put this into a switch statement would be great. Thanks
You can make this a
switch, but it’s unclear why you would want to. On first glance, this isn’t the kind of situation (selecting amongst a set of values and doing something different for each of them) that you useswitchfor.Here’s how, though I don’t recommend it:
This works in JavaScript, but not in most other languages that have
switch. The reason it works is that thecaselabels are evaluated when the execution point reaches them, and they’re guaranteed to be evaluated in source code order. So you’re switching on the valuefalse, which will first be tested (using strict equality,===) against the return value of!error1(num, a_id), and then if that doesn’t match, against!error2(num, a_id), etc.; if none of them matches, then they all evaluatedtrue, and the code in thedefaultblock runs.