Skip to content
Advertisement

Why I can’t do with Switch-Case what I do with If-Else in JS?

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;
       }            
    })
})

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement