How can check the null or undefined values

How to determine if one variable of the payload is undefined or null in JavaScript then must not send it to DB.

In a function node, you could do something like:

if (typeof msg.payload.myVal != 'undefined' && msg.payload.myVal !== null) {
   return msg;
}

Or alternatively, you can use a switch node with the 'not null' condition.

2 Likes

Thank @kuema

Very often also NaN, +/-infinite cause problems. Therefore I use this small function:

isTruthy: input => {
    return !(typeof input === 'undefined' || input === null ||
      (typeof input === 'number' && !Number.isFinite(input)))
  },

... and for properties (example msg.payload.result --> isValidProperty(msg, ['paylaod', 'result']

isValidProperty: (nestedObj, pathArray) => {
    const property = pathArray.reduce(
      (obj, key) => (obj && obj[key] !== 'undefined' ? obj[key] : undefined),
      nestedObj
    )
    return isTruthy(property)

The value 'undefined' denotes that a variable has been declared, but hasn't been assigned any value. On the other hand, Javascript null refers to a non-existent object, which basically means 'empty' or 'nothing'. They're both values usually used to indicate the absence of something . Also, undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object .

9 Likes

This works great for me,

if (typeof msg.payload.myVal != 'undefined') {
    msg.payload.myVal = 1;
}
return msg;

But, this does not,

if (typeof msg.payload.myVal != 'undefined') {
    msg.payload.myVal = 1;
} else {
    msg.payload.myVal = 0;
}
return msg;

The else never gets called when the condition isn't false.

If I change the != to == and reverse the if and the else blocks it still doesn't work, the else block simply doesn't get called.

My solution was the following:

msg.payload.myVal = 0;
if (typeof msg.payload != 'undefined') {
    msg.payload.myVal = 1;
}
return msg;

I have no idea why, but this information might help someone in the future.

Cheers!