Javascript check for undefined and null

In Javascript, how to check if a value is not undefined or null.

If the typeof variable is string then check to see if it has length.

const hasValue = (value) => {
    let valid = typeof value != 'undefined' &&  value != null;
    if (valid && typeof value === 'string') {
      valid = value.length > 0;      
    }
    return valid;
}

usage:

var message = 'Hello World';
if (hasValue(message)) {
    console.log(message);
}

Comments are closed.