Search code examples
javascriptif-statementisnullorempty

A better way for checking on empty/null/undefined


I'm wondering if I can upgrade my code. I have the following steps: when a title is not found, a book is not available. When some parts of the metadata of a book are not found, the book is still available, but the requested data should be returned as unknown.

var notAvailableMSG = process.env.notAvailableMSG;
var unknownMSG = process.env.unknownMSG;
var bookInfo = [];

// if title is not found = book is not available.
if(bookInfo.title == '' || bookInfo.title == undefined ){
  bookInfo.isbn = isbn;
  bookInfo.title = notAvailableMSG;
  bookInfo.author = notAvailableMSG;
  bookInfo.publisher = notAvailableMSG;
  bookInfo.price = notAvailableMSG;
  bookInfo.currency = notAvailableMSG;
  bookInfo.url = notAvailableMSG;
  bookInfo.releasedate = notAvailableMSG;
  bookInfo.sellable = notAvailableMSG;
}
// Check for other empty values
if(bookInfo.author == '' || bookInfo.author == undefined){
  bookInfo.author = unknownMSG;
}
if(bookInfo.publisher == '' || publisher == undefined){
  bookInfo.publisher = unknownMSG;
}
if(bookInfo.price == '' || bookInfo.price == undefined){
  bookInfo.price = unknownMSG;
}
if(bookInfo.releasedate == '' || bookInfo.releasedate == undefined){
  bookInfo.releasedate = unknownMSG;
}

Can this code be written in a better way to let this piece of code run faster (make it more readable)?


Solution

  • When I have long lists of properties, I prefer avoiding repeated code or repeated ifs, if possible.

    In this kind of scenarios I would go with something like:

    var properties = [
      'author',
      'publisher',
      'price',
      'currency',
      'url',
      'releasedate',
      'sellable'
    ];
    
    if(!bookInfo.title) {
      bookInfo.isbn = isbn;
      bookInfo.title = notAvailableMSG;
      properties.map(function(prop) {
        bookInfo[prop] = notAvailableMSG;
      });
    }
    
    // Check for other empty values
    properties.map(function(prop) {
      if(!bookInfo[prop]) {
        bookInfo[prop] = unknownMSG;
      }
    });