Search code examples
javascriptif-statementcase-statementfunction-call-operator

How do I use one function to call the other function by if/case statement?


Does anyone know what typo I made, because my editor, and I can't seem to make it work

number=5;
switch (number) {
    case 5:
        box.onclick = function1;
        break;
    case 50:
        box.onclick = function2;
        break;
}

I've also tried doing it in switch.


Solution

  • With this code:

    number=5;
    switch (number) {
        case 5:
            box.onclick = function1;
            break;
        case 50:
            box.onclick = function2;
            break;
    }
    

    case 50 will never be hit because you set number to 5 before entering the switch block. Therefore box onclick will never equal function2. Therefore, when you click the box, function2 will not be run. Is this really an accurate representation of your actual code, or is it a simplification that has left out important information?