Search code examples
javascriptcallbackconditional-statementsobject-literalhoisting

Does JavaScript hoist if statements when object literals are involved?


var foo = {}; 
document.body.innerHTML = console.log = location.hash = 'Hi ' + '<br>  ' + foo.bar + '<br>  ' + foo.baz; 

setTimeout(function()
           {
  foo.baz = foo["bar"] = []; 
  foo.bar.push(new Date); 
  foo.baz.push(new Date); 
  document.body.innerHTML = console.log = location.hash = 'Hi ' + '<br>  ' + foo.bar + '<br>  ' + foo.baz}, 
           5000);


Solution

  • Since you set node.bar equal to false, (node.foo && node.bar) will evaluate to false whether the properties are attached or not. Rather than checking if those properties are true, you should check whether they are undefined:

    if (typeof node.foo !== 'undefined' && typeof node.bar !== 'undefined') 
    { 
      ...
    } 
    else 
    {
      ...
    }