- Use typeof
let a;
console.log(typeof a === "undefined"); // returns true- Check if a property exists
let favouriteShirt = {
brand: "Superdry"
}
favouriteShirt.colour // undefined
favouriteShirt.styles[0] // TypeError: Cannot read property '0' of undefined
// Use in operator
const colour = "colour" in favouriteShirt ? favouriteShirt.colour : "blue";
// De-construct with defaults
const {styles = ["round neck", "v neck", "deep v"] } = favouriteShirt;- Always initialise your variables
const x = null;
let y = "stuff";- Use default values to your functions or objects
function add(a=0, b=0) {
return a + b;
}
let default = {
fontSize: 12,
color: "black",
paddingTop: 3
};
let custom = {
fontSize: 18
};
let object = {
...default,
...custom
};
object.fontSize // 18
object.paddingTop // 3- Object.is
let someObject;
Object.is(someObject, undefined);- Arrays
let array
if (array && Array.isArray(array)) {
}
I've been badly burned by these undefined variables in javascript. I could easily prevent them by doing the stuff I listed above. In my case using the in operator, assigning default values are the ones I needed to prevent it from stuffing up. Fuck! Very simple but effective.
These pointers are directly taken from https://dmitripavlutin.com/7-tips-to-handle-undefined-in-javascript/. Don't sue me. 🚜