Home > Net >  Why I can't do with Switch-Case what I do with If-Else in JS?
Why I can't do with Switch-Case what I do with If-Else in JS?

Time:05-26

Can you help about the JS DOM example below,

The if-else structure I specified in example 1 works, but the switch-case structure I specified in example 2 does not work. The switch-case structure does not work, although they both function the same. Why ?

Thanks

--- Example 1 / Works ---

fontSizes.forEach(size => {
 
    size.addEventListener('click', () => {
      
        if(size.classList.contains('font-size-1')) {
            .....
        } else if (size.classList.contains('font-size-2')) {
            .....   
        }
        
    })
})

--- Example 2 / Doesn't work ---

fontSizes.forEach(size => {
 
    size.addEventListener('click', () => {
      
      switch (size.classList.contains) {
           case 'font-size-1': 
             ....
           break;
           case 'font-size-2': 
             ....
           break;
       }            
    })
})

CodePudding user response:

You didn't use the switch properly, you're checking size.classList.contains which points to a function with strings (like font-size-1) instead of comparing the actual value.

You can use split (with the includes functions) or use size.classList.contains in each case

Take a look here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/contains How to check className in a switch statement when an element has multiple classes

CodePudding user response:

contains is a method.

So you can't use: switch(size.classList.contains){case 'class1':...}

Instead you should use if(size.classList.contains('class1')){}

If you want a more clean code, you can create an array (or object) for the cases and put ifs on a loop.

CodePudding user response:

Please not that they are not the same. In the first one you are calling function add taking the output whereas in the second one all you are passing via switch statement is the reference to function. The size.classlist.contains is a function which expects an argument. Please know the difference.

  • Related