Salesforce Certified JavaScript Developer free question 7 / 10 · Domain 4: Debugging and Error Handling
A developer runs four operations that fail and logs the name of each error. const checks = [ () => missingValue, () => null.length, () => new Array(-1), () => JSON.parse('{'), ]; for (const check of checks) { try { check(); } catch (err) { console.log(err.name); } } Which sequence of names is logged? (missingValue is not declared anywhere.)
- ReferenceError, TypeError, SyntaxError, RangeError
- ReferenceError, TypeError, RangeError, SyntaxError
- TypeError, ReferenceError, RangeError, SyntaxError
- ReferenceError, RangeError, TypeError, SyntaxError
Show the answer and explanation
Answer: B
Why this is correct
An undeclared name raises a ReferenceError because the variable does not exist in the current scope. Reading a property of null uses a value in an inappropriate way, which is a TypeError. An array of illegal length created with the Array constructor throws a RangeError, and JSON.parse throws a SyntaxError for text that is not valid JSON.
Why the other options are wrong
"ReferenceError, TypeError, SyntaxError, RangeError" … An array of an illegal length created with the Array constructor throws a RangeError, and invalid JSON passed to JSON.parse throws a SyntaxError, so the last two names are swapped here.
"TypeError, ReferenceError, RangeError, SyntaxError" … Reading a variable that does not exist in the current scope throws a ReferenceError, while a property read on null is a value used in an inappropriate way, which is a TypeError. The first two are swapped.
"ReferenceError, RangeError, TypeError, SyntaxError" … A property read on null is a value used in an inappropriate way and throws a TypeError, while the illegal array length throws a RangeError. The middle two are swapped.
Key points
Match the error name to its cause: missing variable, ReferenceError. Wrong kind of value, TypeError. Value out of range, RangeError. Invalid syntax or JSON, SyntaxError.