A save is only text, and text can get damaged. When Sam’s save was cut off partway through the first recipe, JSON.parse() threw an uncaught SyntaxError, main.js stopped at that line, and the list stayed empty.
In this video, you wrapped the load in try and catch and followed, line by line, where JavaScript goes. Here are the key points:
- The
trystatement is for code that might throw. The risky lines go inside the braces oftry. Thecatchblock after them runs only if something insidetrythrows. The name in the parentheses ofcatch, such aserror, holds the error that was thrown. Itsnameproperty is the error’s type, such as"SyntaxError"for bad JSON. - When a line in
trythrows, JavaScript leavestryat that line and jumps straight tocatch. With the damaged save, the Console showedparsing the save,caught a SyntaxErrorand5 recipes loaded, but neverparsed it. The throw came before the assignment, sorecipesstill held the starter recipes, and the page showed those five with no uncaught error. - When
catchfinishes, JavaScript carries on after the whole statement. Watch out:catchnever sends JavaScript back intotry. Anything that must still happen goes after the statement, or, iftryorcatchreturns, infinally. - When nothing throws, every line in
tryruns andcatchis skipped. With a good save, the Console showedparsing the save,parsed itand6 recipes loaded. - A
finallyblock comes last and runs aftertryor aftercatch, whichever path JavaScript took. It runs even whentryorcatchreturns. A line after the statement inside the function never would, so work for both paths goes infinally. - A
returnintryorcatchwaits forfinally, then leaves the function. Thereturnstill picks the value the function hands back, but the function doesn’t finish untilfinallyhas run. Any lines after the statement inside the function are skipped. - Both paths logged
load finishedbefore the recipe count. With a good save,loadRecipes()loggedparsed itandload finishedbefore the line after the call logged6 recipes loaded. With the damaged save, it loggedcaught a SyntaxError,load finishedand5 recipes loaded.
Here’s the loading code from the end of the video, in recipes/main.js under starterRecipes. The labeled logs are only there to show which lines run:
recipes/main.js
function loadRecipes() {
const savedText = localStorage.getItem("recipe-box");
try {
const saved = JSON.parse(savedText);
console.log("parsed it");
return saved ?? starterRecipes;
} catch (error) {
console.log(`caught a ${error.name}`);
return starterRecipes;
} finally {
console.log("load finished");
}
}
const recipes = loadRecipes();
console.log(`${recipes.length} recipes loaded`);