0

I have an endpoint in my node app and I am doing the following...

app.put('/api/authentication', function(req,res){            
    console.log(global.ff);  //undefined
    console.log(req.ff);     //undefined
    console.log(blah);       //throws error    
});

I don't understand why the first two give me 'undefined'. They should throw an error as I have never once declared them. But it's as if node.js has magically declared them and that is why they do not throw an error like the last one...Can someone explain?

RevanProdigalKnight
  • 1,316
  • 1
  • 14
  • 23
Exitos
  • 29,230
  • 38
  • 123
  • 178

2 Answers2

2

There's a difference between undefined and "non-existent"

In the first two lines, global and req are existing variables, they just don't have the keys that you're asking for - so you get undefined.

However, blah simply doesn't exist - node has no place to even ask for the key you're looking for. Note that you can test for undefined as per this answer.

If you had defined blah above, but set no value to it (var blah;), you'd get another undefined error there instead.

Community
  • 1
  • 1
Avery
  • 2,270
  • 4
  • 33
  • 35
  • yes but how did node know to do 'var ff' for the req or the global objects then? – Exitos Jul 08 '14 at 20:29
  • 1
    @Exitos `req` is a parameter to the function you are in, and `global` is predefined by node. the `ff` property is still undefined in both cases, but referencing an undefined *property* doesn't throw an error. – Kevin B Jul 08 '14 at 20:46
  • @Exitos It didn't "do" `var ff;` for the locals OR the global. Objects in javascript have keys, and these keys point to values. While a key may have a value or another object, if the key is undefined, as above, then execution stops there and the value `undefined` is returned. – Avery Jul 09 '14 at 00:03
0

global and req are existing variables.

Asking for a key in existing variable returns it, and if not found - tells that the key is undefined.

Next code will return undefined as well:

var blah = "";
console.log(blah.blah);
alandarev
  • 8,349
  • 2
  • 34
  • 43