Typescript if statement
Created By: chatGPT
In TypeScript, the
if
statement is used to perform conditional execution of code based on whether a specified condition is true or false. The general syntax is as follows:if (condition) {
// code to be executed if condition is true
}
You can also extend the
if
statement with an optional else
clause. This allows you to define an alternative block of code that runs when the condition is false.if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
For more complex conditions, you can use
else if
to check multiple conditions in sequence. The code block will evaluate the conditions from top to bottom.if (condition1) {
// code for condition1
} else if (condition2) {
// code for condition2
} else {
// code if none of the conditions are true
}
Here's an example of using an
if
statement to check if a number is positive, negative, or zero:let number: number = -5;
if (number > 0) {
console.log('The number is positive.');
} else if (number < 0) {
console.log('The number is negative.');
} else {
console.log('The number is zero.');
}
In this example, the program evaluates the variable
number
. It will output 'The number is negative.' because -5
is less than zero.let number: number = -5;
if (number > 0) {
console.log('The number is positive.');
} else if (number < 0) {
console.log('The number is negative.');
} else {
console.log('The number is zero.');
}
Remember to use brackets
{}
to enclose the code blocks within your if
, else if
, and else
statements for clear structure and readability.if (condition) {
// do something
} else {
// do something else
}