How to use Shortcuts for Conditional Operations? 💻
Have you ever come across that huge code filled with if
, else
? Sometimes, this kind of code can be confusing and hard to read. But don't worry! There's a simpler way to write conditional operations in Javascript: shortcuts!
What are shortcuts?
Shortcuts are handy tools we can use to simplify our code. In Javascript, we can use logical operators &&
and ||
to make conditional operations more clear and concise.
The &&
operator
The &&
operator is used to make a "and" conditional operation. In other words, it only returns true
if both conditions are true.
For example:
if (age >= 18 && hasDriverLicense) { console.log('You can drive!');}
We can simplify this code using the &&
operator:
if (age >= 18 && hasDriverLicense) console.log('You can drive!');
The ||
operator
On the other hand, the ||
operator is used to make an "or" conditional operation. It returns true
if at least one of the conditions is true. But be careful! If the first condition is already true, it won't check the second condition.
For example:
if (age >= 18 && hasDriverLicense) console.log('You can drive!');
We can simplify this code using the ||
operator:
if (age >= 18 && hasDriverLicense) console.log('You can drive!');
But what if the second condition is important?
If the second condition is important, we can use a technique called "short-circuit evaluation".
This technique works like this: if the first condition is already true, the ||
operator won't check the second condition. But if the first condition is false, it will check the second condition.
For example:
if (hasEnoughMoney || (hasCreditCard && cardLimit > purchaseValue)) { console.log('You can make this purchase!');}
We can simplify this code using short-circuit evaluation:
if (hasEnoughMoney || (hasCreditCard && cardLimit > purchaseValue)) console.log('You can make this purchase!');
Conclusion
Shortcuts are a simple and efficient way to write conditional operations in Javascript.
They make our code cleaner and easier to read, as well as being great for saving time. Try using them in your next projects and see how they can make your life as a developer easier!
Let's go! 🦅