Question

What I want to achieve is clean code with several possible null returns where I'm not returning in more than one place, the code is easy to follow and is not a nested nightmare. For example consider

var topLevel = testdata['key'];//testdata['key'] may be null
var nextLevel = topLevel['subkey']; //topLevel['subkey'] may be null
var subSubLevel = ...

My initial thoughts are to do something like

var topLevel = testdata['key'] || 'error';

This will at least stop the "cannot get x of null" errors but then I'll have a block at the end where I'll need to check if each of these vars is error and if so return null and provide an appropriate error message (probably with an associative object).

Does anyone have a smarter, more concise way of achieving the same end result?

Was it helpful?

Solution

I'd probably do it with JavaScript's curiously-powerful && operator (the cousin of the curiously-powerful || operator you're already using):

var topLevel = testdata['key'];
var nextLevel = topLevel && topLevel['subkey'];
// ...

If topLevel is falsey (null, undefined, and so on), nextLevel will get that falsey value (the left-hand operand); if not, the right-hand operand is evaluated and nextLevel receives the value of that. Using these kinds of guards, you can keep going as long as you want.

var topLevel = testdata['key'];
var nextLevel = topLevel && topLevel['subkey'];
var nextNextLevel = nextLevel && nextLevel['key3'];
var nextNextNextLevel = nextNextLevel && nextNextLevel['key4'];

This is really handy when you're expecting an object reference, null, or undefined.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top