Get the App
SLTechnology News&Howtos  ›  Development  › 

How js replaces if/else with switch case

Shulou Source: shulou.com Published: 2022-06-01 05:55:24 09月16日 Update

This article is about how js replaces if/else with switch case. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Replace if/else with switch case

Switch case performs better than if/else, and the code looks clearer.

If (1 = = month) {days = 31;} else if (2 = = month) {days = IsLeapYear (year)? 29: 28;} else if (3 = = month) {days = 31;} else if (4 = = month) {days = 30;} else if (5 = = month) {days = 31;} else if (6 = = month) {days = 30;} else if (7 = month) {days = 31;} else if (8 = month) {days = 31;} else if (9 = month) {days = 30 } else if (10 = = month) {days = 31;} else if (11 = = month) {days = 30;} else if (12 = = month) {days = 31;}

Use switch...case to overwrite:

Switch (month) {case 1: days = 31; break; case 2: days = IsLeapYear (year)? 29: 28; break; case 3: days = 31; break; case 4: days = 30; break; case 5: days = 31; break; case 6: days = 30; break; case 7: days = 31; break; case 8: days = 31; break; case 9: days = 30; break Case 10: days = 31; break; case 11: days = 30; break; case 12: days = 31; break; default: break;}

It looks a little more concise. You can rewrite if...else using arrays or objects as appropriate.

Thank you for reading! This is the end of this article on "how js uses switch case to replace if/else". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Tags: Content more article good practical concise code object performance situation array article see knowledge reference help related Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Docker Shulou Tech Info OPPO Reno macOS