Arun Sangal Arun Sangal - 5 months ago 23
Javascript Question

NodeJS / JavaScript if statement not working

NodeJS (latest).

I have the following code. Why the first IF statement is not working as expected? The control doesn't go inside first IF statement.

I see valid console.log output for the first line in the following code and was expecting the first IF statement should execute its code too. But it doesn't; the 2nd IF statement works.

console.log("-- inside create IP() qData['osType'] is set to :: " + qData['osType'])
//--
if ( qData['osType'] == 'undefined' ) {
console.log("1 -- setting qData['osType'] = Linux by default for now. This should happen automatically.")
qData['osType'] = 'Linux'
console.log("1 -- inside create IP() if-statement-qData['osType'] and qData['osType'] is set to :: "+qData['osType'])
}
if ( typeof qData['osType'] == 'undefined' ) {
console.log("2 -- setting qData['osType'] = Linux by default for now. This should happen automatically.")
qData['osType'] = 'Linux'
console.log("2 -- inside create IP() if-statement-qData['osType'] and qData['osType'] is set to :: "+qData['osType'])
}
qData['osType'] = 'Linux'
//--

Answer

If you're checking for undefined-ness you can do one of:

  • typeof foo === 'undefined'
  • foo === undefined
  • foo === void 0

Anything else is not actually (strictly) checking for an undefined value (including comparing a value directly with the string 'undefined').