NodeJS complains that an object is undefined if it's been set in an if statement

I have the following code:

var inNode = function () {
  return (typeof module !== 'undefined' && module.exports) ? true : false;
};

if (inNode()) {
  global.TestObj = { 'test' : 'hello!' };
} else {
  var TestObj = { 'test' : 'hello!' };
}

console.log(TestObj);

TestObj will return as undefined.

I understand in other programming languages that the compiler would complain if you declared a variable inside an if statement and then tried to call it. I didn't think this was the case in Javascript - and if so, where's the error message?!

Cheers!

Due the concept of variable hoisting in JavaScript, all variable declarations are moved to the top of the scope, so your code is actually:

var inNode = function () {
  return (typeof module !== 'undefined' && module.exports) ? true : false;
};
var TestObj;

if (inNode()) {
  global.TestObj = { 'test' : 'hello!' };
} else {
  TestObj = { 'test' : 'hello!' };
}

console.log(TestObj);

Which means that it is defined, but it only has a value if the else block is executed. Otherwise it's undefined.