-2

I don't understand why this doesn't work when the first value isn't available:

var borough = state.city.borough || 'Manhattan';

It returns:

Uncaught ReferenceError: state is not defined

I would expect it to default to Manhattan when state.city.borough isn't defined.

Edit: I am looking for a solution that will work if the "state" object or any of it's keys are not available.

user3006927
  • 484
  • 4
  • 15

4 Answers4

0

Once you fixed the reason why state is declared nowhere you may run into another issue: once state or state.city return null or undefined you will still get an error.

Workarounds are:

  1. check every single member in the chain:

    var borough = (state && 
                state.city && 
                state.city.borough) || 'Manhattan';
    
  2. use something similar to lodash's _.get or write your own version:

    var borough = _.get(state, 'city.borough', 'Manhattan');
    
  3. use destructuring assignment from ES6

     var {city: {borough = 'Manhattan'}} = state;
    
  4. wait until elvis operator is aprooved as part of standard and implemented in major borwsers(or you may apply Babel to use this right now)

    var borough = state?.city?.borough || 'Manhattan';
    

[UPD] missed that point: you have syntax error because state has not been ever defined; not because it's null or something like that

skyboyer
  • 22,209
  • 7
  • 57
  • 64
  • I think you need a `this` someplace or you have the same undefined `state` problem in 1 – JonSG Mar 29 '18 at 19:30
  • @JonSG I agree that those alternatives will not help in case author does not put declaration for `var state` anywhere. – skyboyer Mar 29 '18 at 20:24
0

If state is not declared then it is not declared . However, this is defined so assuming that it is reasonable that at some point to expect state === this.state then try:

var borough = (
    this.state &&
    this.state.city &&
    this.state.city.borough) || 'Manhattan';
JonSG
  • 10,542
  • 2
  • 25
  • 36
-1

This appens because in javascript,if you try to access the property of an undefined object the compiler crashes,so you need to check for the existence of each one of the property you are trying to access:

var borough;

if (state && state.city && state.city.borough) {
  borough = state.city.borough;
}
else {
  borough = 'Manhattan';
}
Alessandro Messori
  • 1,035
  • 1
  • 14
  • 23
  • did you declare the state object somewhere? I assumed that in my answer but if you didn't declare at all the state object of course it will throw an error – Alessandro Messori Mar 29 '18 at 18:23
-2

You can't de-reference an object that is no value, so you have to check for all potentially undefined parts:

var state = undefined;
var borough = state && state.city && state.city.borough || 'Manhattan';
Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170