This is a stage 0 proposal for turning some of the control structures into expressions. Specifically:
For example:
let data = try { JSON.parse(response) } catch { {error: true} };
They are particularly useful on:
Inspired by kotlin, values are taken from the last statement expression (unless it is an undefined
). So, for example:
let a = if (true) {
console.log("hi") // not used
1 // not used
2 // not used
"hello" // used
} else {
false // not used
console.log("hello") // not used
"world" // not used, else never runs
}
// a == "hello"
For for-loops
, an array is returned from the last expression of each iteration. For example:
let odd = for (let number of [1, 2, 3, 4, 5, 6]) {
if (number % 2 == 0) {
// filters all even numbers
continue;
}
number
}
// odd == [1, 3, 5]
Note that turning all of these into expressions enable you to compose them:
let odd = for (let number of [1, 2, 3, 4, 5, 6]) {
if (number % 2 == 1) {
number
}
}
// odd == [1, 3, 5]
We deliberately skip other control structures that don't traditionaly generate values, e.g. break
, continue
, return
, throws
, goto
, etc.
// JSX
var box =
<Box>
{
shouldShowAnswer(user) ?
<Answer value={false}>no</Answer> :
<Box.Comment>
Text Content
</Box.Comment>
}
</Box>;
One can write:
// JSX
var box =
<Box>
{
if (shouldShowAnswer(user)) {
<Answer value={false}>no</Answer>
} else {
<Box.Comment>
Text Content
</Box.Comment>
}
}
</Box>;
let html = lit-html `
<div>
${["apple", "oranges"].forEach(product => lit-html `<span>${product}</span>`)}
</div>
`;
one could write
let html = lit-html `
<div>
${for (let item of ["apple", "orange"]) {
lit-html `<span>${item}</span>`
}}
</div>
`;
let data;
try {
data = JSON.parse(response);
} catch (e) {
data = undefined;
}
One can write:
let data = try { JSON.parse(response) } catch (e) { undefined };
let message;
switch (request.readyState) {
0:
1:
message = "loading";
break;
2:
3:
message = "processing";
break;
4:
message = "done";
break;
default:
message = "error";
}
One can write:
let message = switch (request.readyState) {
0:
1:
"loading";
break;
2:
3:
"processing";
break;
4:
"done";
break;
default:
"error";
}