...

/

Conditional Expressions and Optional Chaining

Conditional Expressions and Optional Chaining

Learn what conditional expressions are and how we can use nested properties through optional chaining.

We'll cover the following...

Conditional expressions

Conditional expressions, also known as ternary expressions, are a feature of JavaScript that allows us to write concise statements that execute different actions depending on a boolean condition. They have the following syntax:

(conditional) ? ( true statement ) : ( false statement );

We can use this JavaScript feature in TypeScript language, which uses a question mark ( ? ) symbol to define the if statement and a colon ( : ) to define the then and else paths.

As an example of this syntax, consider the following code:

const value: number = 10; // Declare and initialize a number variable
// Declare and initialize a string variable that will hold a message
const message: string = value > 10 ?
"value is larger than 10" :
"value is 10 or less";
console.log(message); // Print the message to the console
Conditional message based on value
  • We start by declaring a variable named value on line 1 of type number that is set to the value of 10.

  • We then create a variable named message on line 4, which is of type string and uses the conditional expression syntax to check whether the value of the value variable is greater than 10.

When we run the code, we can see that the message variable has been set to the string value of "value is 10 or less" because the ...