Contenido del Curso
Introduction to TypeScript
Introduction to TypeScript
Complex Conditions
While contemplating how to further complicate the if statement, specifically the condition block, thanks to the benevolent developers of TypeScript and JavaScript, you can now use multiple conditions in a single block.
For example, you need to set two conditions: the number must be greater than 0
AND less than 99
. (For instance, you're a seller of LEGO sets)
let age: number = 80; if (age > 0 && age < 99) { console.log('You can buy a LEGO'); }
As you can see, we've set a double condition. We need the age to be greater than 0
AND less than 99
. To achieve this, we used symbols like &&
. There's another option, which is when we need to set multiple conditions, and any of them can be satisfied. In simpler terms - OR. Let's take a look at an example:
let rate: string = 'Very well!' if (rate == 'Very well!' || rate == 'Good') { console.log('You did a good job!'); }
As you can see, we used ||
to set the OR condition. In our code above, if the grade is Very well
or Good
, then we've done our job well.
Let's quickly remember these keywords:
- AND =
&&
; - OR =
||
.
true && false
=false
;true && true
=true
;false && false
=false
;true || true
=true
;true || false
=true
;false || false
=false
.
By the way, you can use multiple such conditions simultaneously. For example, you may need 3 or 4 of them. For instance, if we need to retrieve a number between 20 and 50 OR
between 70 and 100:
let num: number = 25; if ((num > 20 && num < 50) || (num > 70 && num < 100)) { console.log("I don't know what to write here, YOU WON!") }
We can group conditions in parentheses, just like in mathematics. This means that conditions within the parentheses will be checked first, and then conditions outside the parentheses will be evaluated.
¡Gracias por tus comentarios!