Absolutely, it is perfectly safe to do so.
According to the ECMAScript 5.1 specification , it explicitly states:
The production of ThrowStatement: throw [no LineTerminator here]
Expression; is evaluated in the following manner:
- Let exprRef be the result obtained from evaluating Expression.
- Return (throw, GetValue(exprRef), empty).
The terminology used in ECMAScript 6 is consistent with the same terms.
undefined
undeniably qualifies as an expression and can indeed be thrown. An example illustrating this can be found in this fiddle.
However, it's worth noting that throwing undefined
may not be advisable for maintainability reasons. This action provides no insights into the cause of the exception. Opting to throw a string could possibly offer a better approach:
var o = YM.match(/^(\d{4})\-(0[1-9]|1[012])$/);
if (o != null) {
return [o[0], parseInt(o[1], 10), parseInt(o[2], 10)];
} else {
throw "unrecognized date format";
}
Update: Upon reflection, unless the no details needed aspect in your inquiry implies a concealed information scenario, sheer control flow suffices rather than engaging in exception handling complexities. The solution could simply entail:
function splitYearMonth(YM) { // Returns ["yyyy-mm", yyyy, mm]
var o = YM.match(/^(\d{4})\-(0[1-9]|1[012])$/);
if (o != null) {
return [o[0], parseInt(o[1], 10), parseInt(o[2], 10)];
} else {
return [undefined, undefined, undefined];
}
}
Primarily, due to its potential expensive nature, utilizing exception handling for control flow is generally discouraged in Javascript discussions, unlike certain other programming languages like Python.