typeof undefined vs if object && object.property

Edit on GitHub

Check if a property is defined

Setup

var object = {
  randomProp: 'string'
};

Tests

  • typeof undefined

    if(object && object.randomProp){
      console.log('dummy');
    }
    
    if(object && object.notExistent){
      console.log('dummy');
    }
  • if object && object.property

    if(typeof object.randomProp !== 'undefined'){
      console.log('dummy');
    }
    
    if(typeof object.notExistent !== 'undefined'){
      console.log('dummy');
    }