Skip to content

Instantly share code, notes, and snippets.

@loujaybee
Last active October 12, 2015 10:48
Show Gist options
  • Save loujaybee/75dbf692dbd6facbfdc3 to your computer and use it in GitHub Desktop.
Save loujaybee/75dbf692dbd6facbfdc3 to your computer and use it in GitHub Desktop.
Errors in nested object property access

When getting this error:

errorStack: TypeError: Cannot read property 'length' of undefined 
at get (https://prodtest.mudano.com/core/tasks.data.service.js:9:37)

A solution to this type of error where properties are deply nested in object sub properties, and you're not sure if the property is set up yet is to use _.get

To convert:

if ($rootScope._global.tasks.length > 0)

into:

if(_.get($rootScope, '_global.tasks.length' && $rootScope._global.tasks.length > 0)) {
	// do something
}

and therefore swallow any errors generated when accessing tasks length

#Warning

Be careful though, as sometimes not having properties setup is a good thing and tells us something is wrong elsewhere

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