Skip to content

Instantly share code, notes, and snippets.

@fodra
Last active March 6, 2019 22:27
Show Gist options
  • Save fodra/538db2ecaa9e80705326e42d5499d029 to your computer and use it in GitHub Desktop.
Save fodra/538db2ecaa9e80705326e42d5499d029 to your computer and use it in GitHub Desktop.

Checking if a value is undefined in Javascript

  1. Use typeof
let a;
console.log(typeof a === "undefined"); // returns true
  1. 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;
  1. Always initialise your variables
const x = null;
let y = "stuff";
  1. 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
  1. Object.is
let someObject;
Object.is(someObject, undefined);
  1. Arrays
let array

if (array && Array.isArray(array)) {

}

Conclusion

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.

@fodra
Copy link
Author

fodra commented Feb 24, 2019

These pointers are directly taken from https://dmitripavlutin.com/7-tips-to-handle-undefined-in-javascript/. Don't sue me. 🚜

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment