4 ms·
The traditional way is more readable, I agree. I think it has more to do with statefulness. let example if (someCondition) { example = 3 }
by andyfleming 9y ago
The traditional way is more readable, I agree. I think it has more to do with statefulness.
let example
if (someCondition) {
example = 3
} else {
example = 4
}
In javascript, for example, like above, I'm initializing a variable (with let, allowing reassign-ability). Its value can be modified later by other code.
Alternatively, I could use a ternary operator and a const to avoid potential unwanted reassignments.
const example = (someCondition) ? 3 : 4
------------
Some languages, like Kotlin, actually let you use an if-else expression in a single line...
val max = if (a > b) a else b
... or even allow you to return the last line of a block to assign a value:
val max = if (a > b) {
print("Choose a")
a
} else {
print("Choose b")
b
}
*val, in Kotlin, is similar to const in javascript; it's not reassignable.