TIL Preventing code crash
POSTED ON:
TAGS: javascript
You can prevent a code crash by defining the variable as undefined
.
// WONT WORK
const found = [{ name: "Alex" }].find(i => i.name === 'Jim');
console.log(found.name);
// TypeError: Cannot read property 'name' of undefined
// WILL WORK
const found = [{ name: "Alex" }].find(i => i.name === 'Jim') || {};
console.log(found.name);
// undefined
Via https://dev.to/gigantz/9-javascript-tips-tricks-to-code-like-a-wizard-559i
Related TILs
Tagged: javascript