switch statement in JavaScript is known to have bad effects as in other programming languages. In this post we discuss it's potential impact in server side JavaScript context like NodeJS. For more history on switch please refer Douglas Crockford's YUI blog post.
Let's look at a sample code snippet as in the screenshot below. This is an over-simplistic example. It is a funny little take on an app that reveals it's users the discount code based on their tiers. The logic that will determine the tier of the user and it's category is omitted for benefit of stressing on the issue at hand.
What should have happened was, the basic tier user Valued Customer should have been shown only 10% discount code. Now since our programmer forgot to apply the brakes (i.e. break highlighted in red in the previous case - in hurry or just human error or insufficient knowledge of switch may be), the second case code under case (dis < 5000) triggered leading to giving higher discount to a basic tier customer and showing a not so good message, as in the screenshot below.
Still in this fun app nothing really nasty happened. And the idea was exactly that to take a simple code and demo what switch could lead to.
In real world a similar mistake could lead to serious vulnerabilities - those are hard to detect. More I think of JavaScript, more I believe, coding best practices usually translate to security best practices. To be safe, anti-patterns like implied globals, with, eval, should be avoided.
Let's look at a sample code snippet as in the screenshot below. This is an over-simplistic example. It is a funny little take on an app that reveals it's users the discount code based on their tiers. The logic that will determine the tier of the user and it's category is omitted for benefit of stressing on the issue at hand.
What should have happened was, the basic tier user Valued Customer should have been shown only 10% discount code. Now since our programmer forgot to apply the brakes (i.e. break highlighted in red in the previous case - in hurry or just human error or insufficient knowledge of switch may be), the second case code under case (dis < 5000) triggered leading to giving higher discount to a basic tier customer and showing a not so good message, as in the screenshot below.
Still in this fun app nothing really nasty happened. And the idea was exactly that to take a simple code and demo what switch could lead to.
In real world a similar mistake could lead to serious vulnerabilities - those are hard to detect. More I think of JavaScript, more I believe, coding best practices usually translate to security best practices. To be safe, anti-patterns like implied globals, with, eval, should be avoided.