Conditional statements are fundamental to programming logic, allowing code execution to vary based on whether certain conditions are met. Let's explore how if statements work in Swift, Kotlin, and TypeScript.
Swift
Swift provides several ways to control program flow with conditional statements, most notably the if statement.
let temperature = 25
if temperature > 20 {
print("It's warm")
} else {
print("It's not so warm")
}
//if-else-if chain
if temperature > 30 {
print("It's hot!")
} else if temperature > 20 {
print("It's warm.")
} else {
print("It's cool.")
}
Kotlin
Kotlin's if statement is similar to Swift's, but it can also be used as an expression that returns a value.
val temperature = 25
if (temperature > 20) {
println("It's warm")
} else {
println("It's not so warm")
}
//if-else-if chain
if (temperature > 30) {
println("It's hot!")
} else if (temperature > 20) {
println("It's warm.")
} else {
println("It's cool.")
}
//Using if as an expression
val message = if (temperature > 20) "It's warm" else "It's not so warm"
println(message)
TypeScript
TypeScript's if statements are very similar to those in JavaScript, providing a familiar structure for web developers.
let temperature = 25;
if (temperature > 20) {
console.log("It's warm");
} else {
console.log("It's not so warm");
}
//if-else-if chain
if (temperature > 30) {
console.log("It's hot!");
} else if (temperature > 20) {
console.log("It's warm.");
} else {
console.log("It's cool.");
}
//Ternary operator
const message: string = temperature > 20 ? "It's warm" : "It's not so warm";
console.log(message);
Key Similarities
- Basic Structure: All three languages use the same basic structure for if statements: if condition {} else? {}.
- Chaining: else if (or similar) is used to chain multiple conditions.
- Boolean Conditions: The conditions within the if statements must evaluate to a boolean value (true or false).
Key Differences
- Truthy/Falsy: TypeScript, like JavaScript, has the concept of "truthy" and "falsy" values, which can be used in if conditions. Swift and Kotlin require explicit boolean values.
- if as Expression: Kotlin allows the if statement to be used as an expression, returning a value.
Top comments (0)