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);
Asked
Active
Viewed 423 times
-1

Paul Sweatte
- 24,148
- 7
- 127
- 265
-
1It should work. The 'if' fails because the end result is 'falsy'. But this is surely valid in js. – vishakvkt Apr 27 '13 at 00:21
-
The condition was made up, but I've had this experience more than once when the method in question is called after an AJAX request. – Paul Sweatte Apr 27 '13 at 00:25
-
1Could you show a concrete example, a working demo on jsfiddle maybe? – bfavaretto Apr 27 '13 at 00:25
-
Not right now. If the problem persists, that's the next logical step. – Paul Sweatte Apr 27 '13 at 00:30
-
1AJAX... asynchronous... yada, yada, yada – Apr 27 '13 at 00:31
-
If it has to do with the asynchronous nature of the call, how does declaring the keys statically versus dynamically fix the problem? – Paul Sweatte Apr 27 '13 at 00:36
-
First, I have no idea if it has to do with the async nature of the call, because you've not given an example of what "it" actually is. That said, as far as I know, you're creating the object, making the AJAX call, updating the object in the callback, but trying to log the new properties outside the callback. I'm not clear on what the debugger's display of properties has to do with your `if` statement though. – Apr 27 '13 at 00:41
-
When I update the object, then try to access them immediately afterwards, they are not showing up in the object when I step through the code. So the question is why are they `undefined` at this point, as noted in the answer below. – Paul Sweatte Apr 27 '13 at 01:18
2 Answers
1
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
{
...
}

ljfranklin
- 480
- 3
- 12
0
Looks like it may be implementation dependent:
The object that may be created in step 1 is not accessible outside of the above method. An implementation might choose to avoid the actual creation of the object. The only situation where such an actual property access that uses this internal method can have visible effect is when it invokes an accessor function.
So instead of accessing the property, stringify and pass by value.
References

Paul Sweatte
- 24,148
- 7
- 127
- 265