Exercise · Errors · lesson 9 of 10
Exercise: JSON or a fallback
Write a function function parseJsonOr(text, fallback, check) that parses a JSON string, passes the resulting value to the function check and returns that value. If text is not valid JSON, the function does not throw an error but returns fallback. An error thrown by check comes out of the function unchanged.
parseJsonOr("[1, 2]", [], () => {})→[1, 2]parseJsonOr("{ bad", "none", () => {})→"none"parseJsonOr('"hi"', 0, mustBeNumber)→ throws theTypeErrorthatmustBeNumberthrew: it checks that the value is a number
Constraints: text is always a string, possibly empty (which is not valid JSON); the value from valid JSON is returned even when it is null, false or 0; fallback is returned as is, without calling check.
Do not add extra imports unless the task says so explicitly.
Subscribe to take the course
The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.