Conditional statements allow you to check a certain condition and, depending on the result of the check, execute certain actions.
Depending on the condition in the first operand, the ternary operation returns the second or third operand. If the condition in the first operand is true, then the second operand is returned; if the condition is false, then the third one.
const a = 1; const b = 2; const result = a < b ? a : b; console.log(result); //1
Here the first operand represents the next condition a < b. If the value of the constant a is less than the value of the constant b, then the second operand is returned – a, that is, the constant result will be equal to a. If the value of the constant a is greater than or equal to value of the constant b, then the third operand is returned – b, so the constant result will be equal to the value of b.
Operator ?? (nullish coalescing operator) allows you to check the value for null and undefined. It takes two operands.
The operator returns the value of the left operand if it is NOT null and undefined. Otherwise, the value is returned right operand. For example:
const result1 = "hello" ?? "world"; console.log(result1); // hello
Operator ?? has a modification in the form of the ??= operator, which also allows you to check the value for null and undefined.
If the left operand is null and undefined, then it is assigned the value of the right operand. Otherwise, the left operand retains its value. For example:
let message = "Welcome to JavaScript"; let text = "Hello work!" text ??= message;