Reputation: 17326
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'
//--
Upvotes: 0
Views: 916
Reputation: 106698
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'
).
Upvotes: 3
Reputation: 841
In your first if statement, qData['osType']
evaluates to undefined
, but your comparison is checking whether undefined == "undefined"
. The string literal has a value and therefore isn't equal to undefined
.
In your second if statement, typeof qData['osType']
evaluates to the string "undefined"
, so the expression evaluates to true
and your code block is executed.
Upvotes: 2
Reputation: 5225
I think
qData['osType'] == 'undefined'
must be rewrite as
qData['osType'] == undefined
My prefer to check
if(!qData.osType)
Upvotes: 1