Michel
Michel

Reputation: 11755

Testing undefined, failing in JS

In an Express app I have the following JS code (server side) in a middleware to check that a user provides an adequate token. This is only the relevant part for my question:

const authHeader = req.headers['authorization']
console.log("authHeader : ", authHeader)

if (authHeader === undefined) console.log("authHeader === undefined")
else console.log("authHeader !== undefined")

if (authHeader == undefined) console.log("authHeader == undefined")
else console.log("authHeader != undefined")

if (authHeader.valueOf() === undefined) console.log("authHeader === undefined")
else console.log("authHeader !== undefined")

if (authHeader.valueOf() == undefined) console.log("authHeader == undefined")
else console.log("authHeader != undefined")

if (typeof authHeader === 'undefined') console.log("authHeader === undefined")
else console.log("authHeader !== undefined")

if (typeof authHeader == 'undefined') console.log("authHeader == undefined")
else console.log("authHeader != undefined")

As one can see the code above does not do much, except getting an incoming parameter, and testing it, but here is the result in the server logs:

app[web.1]: authHeader :  undefined
app[web.1]: authHeader !== undefined
app[web.1]: authHeader != undefined
app[web.1]: authHeader !== undefined
app[web.1]: authHeader != undefined
app[web.1]: authHeader !== undefined
app[web.1]: authHeader != undefined

The console.log() shows that authHeader is undefined. But none of the following tests confirms that. They all show authHeader as not undefined.

Why is that ?

I have used all the possible ways I could think of to do the test but it seems they are all wrong.

P.S.

Knowing the way I do the test, I expect authHeader to be undefined.

What I do not expect is that none of the test would say so.

Upvotes: 0

Views: 40

Answers (0)

Related Questions