Today I will be going over some really helpful tips I found to be particularly interesting when I implemented them myself and hopefully your reaction will be just like the GIF above :)
An if/else statement is an expression that checks if a condition is “truthy” or “falsy”. Here is an implementation of an if/else expression.
The better way….
Ternary operations are frequently used in replacement of conditional if statements. Where the operation checks if the condition is “truthy” or “falsy”. The question mark checks to see whether it is true or false. Followed by if the condition is “truthy” the first expression is executed. Then if the condition is “falsy” the expression after the colon is then executed.
Accepting Multiple Options
Sometimes we come across multiple options that can be presented depending on what we are looking for. Below is an if/else statement checking to see which conditional is “truthy”…
This one is better we use a switch case that evaluates an expression to see if it matches a given case as below…
Here is an if/else statement just like the others above to assign a variable…
Here is a better way using a short-circuit evaluation with operators such as “||” which means OR. Here I decided not to define “selectedFood”, which leaves it “falsy”, for demonstration purposes. It says favFood equals the selectedFood OR “No….fav..” and since selectedFood is “falsy” it defines favFood as so…
Object Destructuring Assignment
Objects have keys with values and sometimes to get those values you need to assign a variable as so….
Now instead of creating multiple variables in numerous amounts of lines you can write it in one line giving you the same output as above….
There are a vast amount of ways all of these can be used and I honestly wouldn’t be surprised if there are better implementations of all of these (I’m sure there are). For me developing has been so much about exploration and learning so much from it that I really enjoy it. I hope this helps and you’ve learned something and possibly got the popcorn out too! lol Thanks for reading! :)
Below are some resources I came across that elevated my understandings…
Learn how to use logical OR ( || ) to your advantage when assigning variables.