Cannot read property of undefined

October 11, 2022

Undefined variable frustrating programmer
Photo by Tim Gouw on Unsplash

Undefined properties are the cause of many errors. Below are a few ways to deal with undefined properties of objects in your code.

#1 Destructure

Destructure the property but provide a default value

  Some code...
  const coords = getCoordinates() 
  // default to New York City
  {((lat = '40.730610'), (lon = '-73.935242'))} = coords

Destructuring allows assignment of properties directly. If you supply an equals sign and a value then your variable gets that as a default. It protects your code from undefined values.

#2 Check for the property

Do a check before continuing with your code. This will allow you to skip code or supply different values instead of letting your code run into errors.

  Some code...
if (e.target.className && typeof e.target.className.includes !== 'undefined') {
  // run your code here
}

The typeof keyword allows for type comparisons with their string representations a few types include 'undefined', 'boolean', 'number' ...etc

A check like this will ensure code will only run if the property is no longer undefined.

# 3. Use default values

Providing default values is a solid way to make sure the property can't be undefind or null. Whenever the style is checked the

  Some code...
const homeModalProps = { color: 'red' }
const aboutModal = {
  fontFamily: 'Arial, Helvetica, sans-serif;',
  color: 'black',
}

const styles = {
  ...homeStyles,
  ...aboutStyles,
}

// returns 'black'
style.color

The spread syntax (...) here takes all of the iterable properties and puts them into the styles object.

# 4. Use the nullish coalescing operator

This handy symbol can handle null and undefined checks by itsel. It's very terse!

  Some code...
const options = { age: 2000 }
options.timeout ?? 4000

The nullish coalescing operator returns the right side when the left side is null or undefined. So if options.timeout was already set this statement will have no effect. The lefthand side will be returned and you can be assured the value isn't null. If the property 'timeout' was null then options.timeout will equal 4000. No more undefined values here.