Summary Notes on Truthy & Ternary Concepts in Javascript

A breakdown of Truthy & Ternary Concepts in Javascript.
Truthy & Falsy Evaluations
Taking the notion that when a variable is created, even without being assigned a value, it can still be evaluated. Most un-assigned values to variables are evaluted as false and thus can be said to be Falsy. See below list for examples. When a variable is assigned a value, (Not matching the exmaples from the list) the variable is evaluated to true. And it can be said that the variable is Truthy.
Example of Falsy evaluated values are as follows:
- 0
- Empty strings like "" or ''
- null which represents when there is no value at all
- undefined which represents when declared variable lacks a value.
- NaN, or Not a Number.
Example Code Block
|
Truthy and Falsy Assignment
You can write shorthand code for some forms of variable assignements, using logical operators, and Short-circuit evaluation. For example if you take the code block for username assignment to a variable.
|
Using logical operation as well as Truthy & Falsy assinment priciples whe can simplify this to a line.
|
Because || or statements check the left-hand condition first, the variable defaultName will be assigned the actual value of username if is truthy, and it will be assigned the value of ‘Stranger’ if username is falsy. This concept is also referred to as short-circuit evaluation.
Another Example Block
|
Ternary Operator
The ternary operator allows for a compact syntax in the case of binary (choosing between two choices) decisions. It accepts a condition followed by a ?
operator, and then two expressions separated by a :
. If the condition evaluates to truthy, the first expression is executed, otherwise, the second expression is executed.
|
Other Example code blocks
|