Chris Staudinger
Chris Staudinger

@ChrisStaud

7 تغريدة 3 قراءة Oct 13, 2022
Programming alternatives to if...else statements in JavaScript 🧵👇
Control flow is the order in which a machine executes code.
Conditionals like the if…else statement change the control flow.
Some other conditional structures include:
1. Jump/dispatch table
2. Switch statement
3. Ternary operator
4. Dynamic dispatch
Let’s dive in👇
1. Jump / Dispatch Table
Stores value-function pairs in an object to quickly fetch and run a function based on a value (which is treated as an object key).
Quite an advanced conditional structure.
In the right context, this programming approach is a very elegant solution 💡
2. Switch Statement
Finds the matching value of an expression and executes the code block associated to the matching value.
In JavaScript, if you have multiple conditional branches, a switch statement is much cleaner than chaining ‘else if’ statements 💡
3. Ternary Operator
Checks a condition and executes the first expression if the condition is true. Otherwise it runs the second expression.
Very clean approach when you have only two options to return/execute based on a condition.
Used heavily in React conditional rendering.
4. Dynamic Dispatch
This pattern involves selecting which polymorphic method to call based on an object’s type.
If you’re code already employs an OOP approach (object oriented programming), then this pattern can be a good choice instead of multiple if statements.
That's the end of this thread.
I simplify software development and getting into tech💡
Follow @ChrisStaud for more free tips and free resources.
If you enjoyed this thread, don't forget to like, comment, and retweet the first tweet.

جاري تحميل الاقتراحات...