Can anyone give a comprehensive reason as to why the following node.js script would be crashing?
var _ = require("underscore");
var foo = {
bar: 123
}
(!_.isNull(foo.bar)?foo.bar = true:"");
The error it produces is:
TypeError: Cannot read property 'bar' of undefined
at Object.<anonymous> (/Users/blahsocks/test_ob.js:7:15)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
I can fix the issue by adding a console.log(foo)
before the "if" or if I change the if to (typeof ob.bar !== "null")
but I wondered if there was a reason this would be causing an error.
Automatic semicolon insertion has hit you.
Your code is interpreted as
which is a function call in an assignment. Even before you would get an error that
{bar:123}
is not a function, you are getting an exception because you are accessing a property onfoo
before it is assigned a value to (and is stillundefined
).To fix this, use
(where both the semicolon and omitting the parenthesis would have fixed the issue alone).