A code block like this yields a value in chrome console and repl
{
let x = 1;
for (let i = 1; i < 10; i += 1) {
x *= i;
}
x;
}
Is it possible to assign the result of a block to a variable?
This will throw an error because {}
is interpreted as an object here
const a = {
let x = 1;
for (let i = 1; i < 10; i += 1) {
x *= i;
}
x;
}
3
Answers
It seems like eval works (I know that eval is evil)
JavaScript does not have block expressions as some other languages do. As you noted, it becomes an object/error.
What you could do is use an IIFE and return a value from it.
The point of blocks has greatly increased now that
const
andlet
have much more robust scoping rules overvar
. It also would be useful with the newusing
support as well.You have to write a function, or similar.