I had a situation like code below and since it's an arrow function and for a single line of code in arrow functions , no curly braces are required, I didn't use that and It works just fine.
const test = new Promise((resolve, failure) => {
failure("mistake");
});
const handler = test.catch(() => console.log("it's ok"));
but in code below when I typed throw without any curly braces, it just threw an exception:
const test = new Promise((resolve, failure) => {
failure("mistake");
});
const handler = test.catch(() => throw new Error("it's not ok"));
but just after adding curly braces to throw, it started to function correctly again:
const test = new Promise((resolve, failure) => {
failure("mistake");
});
const handler = test.catch(() => {throw new Error("it's not ok")});
so I wonder why throw needs curly braces under any circumstances?
More accurately, for a single expression, no curly braces are required. The critical question is: what is an "expression"?
An expression is a piece of code that resolves to some value. So for example,
2 + 3is an expression; it calculates and then resolves to 5.console.log("it's ok")is an expression; it calls a function then resolves to the function's return value (in this case,undefined).But something like
let x = 2 + 3is not an expression. It does contain an expression (the2 + 3part), but the full thing is a "statement". Statements do not resolve to a value, and so they can't really be combined with other things For example,console.log(let x = 2 + 3)orlet y = (let x = 2 + 3)are not legal.The code
throw new Error("it's not ok")is a statement; it does not resolve to a value. Thus, it cannot be used in spots that require an expression. You can't dolet x = throw new Error("it's not ok"), and you can't omit the curly braces of your arrow function.