3 ms·
Does JavaScript have regular blocks? There are a number of times where I want to put a small amount of local logic in a block without having to put into an anon
by eatonphil 5y ago
Does JavaScript have regular blocks? There are a number of times where I want to put a small amount of local logic in a block without having to put into an anonymous function called immediately and without moving that logic further up in code.
A specific example of this is doing some small custom callback logic in d3 configuration.
foo: {
const f = 1;
f
}
Versus:
foo: (() => {
const f = 1;
return f;
})()
Blocks are common in other expression-oriented languages like Scheme, Ruby, Rust, and Standard ML. I would like to be able to use that in JavaScript.
- nicoburns 5y agoIt does, but they aren't expressions like you're suggesting. They only thing they do is limit the scope of variable defined inside them (assuming let or const are used. var is not effected). There is a proposal for this under the name "do expressions" because the proposed syntax is like this: foo: do { const f = 1; f } (because a plain block would be ambiguous with object literal syntax in some cases).
- eatonphil 5y agoSweet, thanks for the pointer.
- twhb 5y agoKind of. let x _: { let y = 1 let z = 2 x = y + z } y // <- throws
- eatonphil 5y agoOh yeah. It just doesn't can't return a value.