- if (x) { const y = true } else { const y = false } // y doesn't exist after the block - try { const x = foo } catch (e) { } // x doesn't exist after the try block
- if (x) { const y = true } else { const y = false } // y doesn't exist after the block - try { const x = foo } catch (e) { } // x doesn't exist after the try block
const y = (() => {
if (x) {
return true;
} else {
return false;
})(); const y = (x === true) ? true : false;
I used this kind of style for argument initialization when I was writing JS code, right at the top of my function bodies, due to ES not being able to specify real nullable default values. (and I'm setting apart why I think undefined as a value is pointless legacy). Composite.prototype.SetPosition(x, y, z) {
x = (isNumber(x) && x >= 0 && x <= 1337) ? x : null;
y = (isNumber(y) && y >= 0 && y <= 1337) ? y : null;
z = isNumber(z) ? z : null;
if x !== null && y !== null && z !== null {
// use clamped values
}
}val result = if (condition) { val x = foo() y = bar(x) y + k // return of last expression is return value of block } else { baz() }
Or:
val q = try { a / b } catch (e: ArithmeticException) { println("Division by zero!") 0 // Returns 0 if an exception occurs }
Edit: ugh, can't get the formatting to work /facepalm.
function SetPosition(x, y, z) {
if (!(isNumber(x) && isNumber(y) && isNumber(z))) {
// Default vals
return;
}
x = clamp(x, 0, 1337);
y = clamp(y, 0, 1337);
z = z;
}In JS, errors are pretty painful due to try/catch, that's why I would probably these days recommend to use Effect [1] or similar libraries to have a failsafe workflow with error cases.
Errors in general are pretty painful in all languages in my opinion. The only language where I thought "oh this might be nice" was Koka, where it's designed around Effect Types and Handlers [2]
const y = (bool)x;
or const bool y = x;