How do I make IF statements work? Is there a CASE / SWITCH Equivalent?

Are you sure your inputNumber is a number? switch/case uses strict comparison (===).

is that siteStatus really existent there and is it typeof integer ?

It is a number being returned by Mongo. Does it need to be converted to a number maybe?

Add a console.log(typeof inputNumber);

try to print it out of that link as just any html text element or something.
To be sure it is not doing something wring with attaching the string to address.
But still I think there will be something wrong with your data types, it expect number

I added a column to my template to show the value of siteStatus, and it does show as a number.

It might show as a number, but is it a number? Add a console.log as I suggested earlier to be sure.

I added this right before the switch statement:

console.log(typeof inputNumber);

The helper now loos like this:

Template.registerHelper('pickColor', function(inputNumber) {
    console.log(typeof inputNumber);

    switch(inputNumber) {
        case 1:
            return "green";
            break;
        case 2:
            return "yellow";
            break;
        case 3:
            return "red";
            break;
    }
  });

In the console, I do get an exception. Maybe needs to be converted to an integer?

Hmm, you shouldn’t get an exception from that extra line.

Defensive programming says you should always supply an appropriate default action in a switch statement. In this case it may be worth logging what you’re actually getting:

switch(inputNumber) {
    case 1:
        return "green";
        break;
    case 2:
        return "yellow";
        break;
    case 3:
        return "red";
        break;
    default:
        console.log(inputNumber);
        break;
}

Thanks @robfallows, that’s what it was. I added parseInt before the switch and it now works correctly!

  Template.registerHelper('pickColor', function(inputNumber) {
    inputNumber = parseInt(inputNumber);
    switch(inputNumber) {
        case 1:
            return "green";
            break;
        case 2:
            return "yellow";
            break;
        case 3:
            return "red";
            break;
    }
  });

You da man! :smiley:

You’re welcome! :smile:

Just a “word to the wise”: you should always specify the radix with parseInt.

1 Like