Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dead code removal from switch cases in JavaScript

Does any compressor take care of removing the switch cases which do not get called anywhere in the application?

function execute_case(id) {
    switch(id) {
    case 0:
       console.log("0");
       break;
    case 1:
       console.log("1");
       break;
    case 2:
       console.log("2");
       break;
    case 3:
       console.log("3");
       break;
    default:
       console.log("default");
       break;
    }
}

execute_case(1);

If the above is all I have, then theoretically cases 0,2,3 are dead code and will never be executed. Does any compressor have the intelligence of removing this code when minifying code?

I am taking a look at a piece of code which has over 200,000 cases in a switch statement, and hence the question.

Thanks, -Vikrant

like image 302
v2b Avatar asked Jul 26 '13 18:07

v2b


People also ask

How do I remove dead code?

The quickest way to find dead code is to use a good IDE. Delete unused code and unneeded files. In the case of an unnecessary class, Inline Class or Collapse Hierarchy can be applied if a subclass or superclass is used. To remove unneeded parameters, use Remove Parameter.

Does switch need break JavaScript?

The break KeywordIt is not necessary to break the last case in a switch block. The block breaks (ends) there anyway. Note: If you omit the break statement, the next case will be executed even if the evaluation does not match the case.

How do you get a switch case off?

Use the break Keyword to Come Out of a Switch Case In JavaScript, the break keyword is used to stop the execution of the switch case and comes out of it. We can apply the break keyword after every case of the switch case if we want to execute only a single case from the switch case.

Can we use switch case in JavaScript?

The switch case statement in JavaScript is also used for decision-making purposes. In some cases, using the switch case statement is seen to be more convenient than if-else statements. Consider a situation when we want to test a variable for hundred different values and based on the test we want to execute some task.


1 Answers

No Sir,

As id is a variable, no compressor will "know" that this can not happen. The compressors do not analyze variable values in switch statements and know how to remove them.

If you "know" these cases will not happen, just remove them yourself.

like image 84
nativist.bill.cutting Avatar answered Nov 03 '22 00:11

nativist.bill.cutting