Mastery of conditional expressions for shorter codes Conditionals are a very important aspect of the syntax of every programming language. If you have been for sometime in any of the popular languages, you should already be familiar with the or conditional statements. They are very useful for making decisions in programs. programming if..elif..else switch For example, let’s say a treasure chest has been designed such that only Glad ( ) should be able to open it. This logic can be programmatically represented (in Python) as follows: that’s me Although, the previous code snippet was written in Python syntax, this article is strictly for . However, most of the techniques shown here may be applied to a couple other programming languages. JavaScript I promise from this moment that you will not find any other line of code in this article written in the syntax of any other programming language besides JavaScript. In this article, more emphases will be laid on conditional expressions (using logical operators) in JavaScript and how they can be used to make codes shorter, than on conditional statements. Expressions vs Statements Before proceeding, you need to be able to distinguish between expressions and statements in JavaScript. Here is a very simple analogy: Expressions are to JavaScript what phrases are to grammar, while statements are to JavaScript what sentences are to grammar. An is any phrase that the JavaScript engine can evaluate to produce a value. expression literals, assignments, function expressions, logical, bitwise or arithmetic operations, object property access, function invocations, eval, etc. For example: The following code snippet show some JavaScript expressions: A is any sentence or command that the JavaScript engine can execute to make something happen or cause some side-effect. statement conditionals, variable or function declarations, loops, throw, return, try/catch/finally, etc. For example: Some JavaScript expressions like and may have side-effects, and as a result can usually be used as statements ( ). assignments function invocations expression statements Conditions and Booleans A critical requirement of every conditional is the . The is what determines the decision to be made in the program. condition condition In JavaScript, this can be any valid expression. Usually, this expression, however complex it is, is evaluated to one of two values called : either or . condition condition booleans true false A proper understanding of how the JavaScript engine converts these expressions to booleans is necessary for writing correct and predictable conditional logic. condition Here are two fundamental concepts that can enable us to understand the conversions: Identifying and values truthy falsy Understanding in logical operations short-circuiting Truthy vs Falsy Every value in JavaScript can be classified as either or . The values in JavaScript are as follows: truthy falsy falsy or or ( ) '' "" `` an empty string or ( ) 0 -0 the number 0 null undefined NaN false Every other value besides the ones in this list are values. Whenever JavaScript expects a boolean value, values are implicitly coerced to while values are implicitly coerced to . truthy truthy true falsy false However, if you want to be deliberate or explicit about the type coercion, you can use the native function to convert any value its corresponding boolean. Boolean You can also use the logical ( ) operator to convert a value to a boolean. The operator converts it’s operand to the inverse boolean value, hence, it always evaluates to a boolean value. NOT ! ! Using the operator evaluates to on truthy values and on falsy values. To convert a value to its corresponding boolean, you need to use the operator twice. ! false true ! Short-Circuiting The ( ) and ( ) logical operators both require two operands, and are used to perform Boolean operations on their operands. AND && OR || Given that the two operands are booleans ( or ), true false operation returns only when both operands are , otherwise it returns . && true true false operation returns only when both operands are , otherwise it returns . || false false true Note that the operator has a higher precedence than the operator, and as such, is usually evaluated first. Hence, when they are used together in an expression, you may use parentheses ( ) for grouping in order to alter the evaluation order. Consider the following code snippet: && || () When using these operators, the first operand is always evaluated. However, the second operand may never be evaluated depending on the result from evaluating the first operand. This behavior is known as . short-circuiting The and operations do not always produce a boolean value. Generally, they can produce just any value. Here is a more concise description of their behavior based on : && || short-circuiting operator first evaluates its first operand. If the resulting value is , it evaluates the second operand and returns its value. However, if the value of the first operand is , the second operand is never evaluated, it just returns the value from the first operand. && truthy falsy falsy operator first evaluates its first operand. If the resulting value is , the second operand is never evaluated, it just returns the value from the first operand. However, if the value of the first operand is , it evaluates the second operand and returns its value. || truthy truthy falsy Replacing Statements with Expressions You now have a clear understanding of the concept and how expressions get converted to booleans. short-circuiting condition Next, you will see how some conditional statements can be converted to simple expressions. You will also see how such conversions can make your code look more compact and shorter. 1. Simple If Statements Very simple statements can easily be replaced with conditional expressions by leveraging on the concept of . Consider the following code snippet: if short-circuiting In this code snippet, the statement ensures that the function is only invoked when the condition evaluates to . if deletePost() true This simple statement can be replaced with a very simple conditional expression as shown in the following code snippet: if Though this conditional expression works in a similar fashion as the previous statement, they are actually different. if The conditional expression produces a value, which means it can be assigned to a variable, or used any other place where a value is required. Remember that using conditional expressions like this means you have to be very careful about short-circuiting caveats. It is very possible that an operand may not be evaluated as we saw in the previous section on short-circuiting. 2. If…Else Statements Consider the following dummy code snippet for determining the strength of a password: The intent of this code snippet is very simple — check if the password is more than 7 characters long. If it is, then set the variable to , otherwise set it to . strength “Strong” “Weak” The previous code snippet can be shortened to the following: This code snippet does exactly what the previous one does, all in just one line. This looks pretty good already. The following code snippet tries to review the evaluation of the conditional expression. There is a better way of writing these kinds of conditional expressions — using the also called the . Its syntax looks like the following: if...else conditional operator ternary operator The previous code snippet can hence be rewritten using the ternary operator as follows: Although the code snippet using logical operators works in a similar fashion as the snippet using the ternary operator (for this example), it is important to know that they are not substitutes. It is much safer to use the for cases like this except you really know what you are doing. ternary operator Consider the following code snippet to understand the danger of using logical operators for cases like this: Here is another very familiar conditional statement that was usually found in cross-browser AJAX libraries. Using logical operators, the previous code snippet can be rewritten like this ( ): indentations are used to aid readability However, using the ternary operator, it can be written like this: . Notice in this code snippet that the ternary operator is nested, which is useful for dealing with more involved _if...else_ conditions Tips and Shortcuts In this section, you will see some helpful tips and shortcuts that can be useful when working with conditions and logical operators. Normalizing to Boolean You have already seen how to explicitly convert a JavaScript value to its equivalent boolean value, either by using the native function or by using the ( ) operators. Boolean double NOT !! Let’s say you want to normalize such that you always get a boolean as follows: value If is a boolean, return as it is. value value If is not a boolean, default to a boolean value of your choice - either or . value true false The following code snippet shows how this can be done ( ): functions are being used here De Morgan’s Laws If you are familiar with Boolean Algebra you should already know about the . These laws also apply to JavaScript logical operators. De Morgan’s laws The following code snippet demonstrates the laws: Boolean Identities When dealing with booleans, there are some known identities that are always true. Given that , and are boolean values, the following code snippet shows some of these identities. A B C Multiple Ternary Operators You have seen in an earlier code snippets that ternary operators can be nested to handle more involved conditional logic. if...else However, there are a few things you need to know about the precedence and associativity of the ternary operator to enable you use them effectively in complex expressions. . Hence it is evaluated last when used together with operators of higher precedence. The ternary operator has a than logical operators and most other operators lower precedence . Hence, when multiple ternary operators are used in the same expression, they are parsed from right to left. The ternary operator has a associativity right-to-left When using multiple ternary operators in an expression, you may need to use parentheses ( ) to alter the evaluation order. Here is an example: () More JavaScript for Experts If you are interested in related articles that expose other ways you can improve your JavaScript codes, then don’t hesitate to go through these articles: Cool JavaScript Shortcuts and Tips for Everyday Use Hacks for Creating JavaScript Arrays JavaScript ES6: 5 new abstractions to improve your code ES6 Destructuring: The Complete Guide JavaScript typeof Conclusion Having reached the end of this article, I’m sure you can now be able to identify areas in your code where these tips and techniques can be applied to improve your code like that of an expert. Clap & Follow If you found this article insightful, feel free to give some rounds of applause if you don’t mind. You can also follow me on Medium ( ) for more insightful articles you may find helpful. You can also follow me on Twitter ( ). Glad Chinda @gladchinda Enjoy coding…
Share Your Thoughts