javascriptecmascript-6

trim string without error even when its null or undefined


I have been wondering whether it is possible without a helper function to trim an attribute that can be a string or alternatively undefined or null without try..catch.

(obj.postcode || "").trim() is the simplest way I could come up with. Is there a different way to do it?

const obj = {}
const inParams = []
const postcode = (obj.postcode || "").trim()
if (!postcode) {
  inParams.push('zip:'+ postcode)
}

Solution

  • You first have to check if obj.postcode exists.

    Try:

    const postcode = (obj.postcode) ? obj.postcode.trim() : "";