Nodejs Object Declaration And Immediate Shorthand If Statement Crashes The App
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.b
Solution 1:
Automatic semicolon insertion has hit you.
Your code is interpreted as
var foo = {
bar: 123
}( !_.isNull(foo.bar)?foo.bar = true:"" );
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 on foo
before it is assigned a value to (and is still undefined
).
To fix this, use
var foo = {
bar: 123
};
!_.isNull(foo.bar)?foo.bar = true:"";
(where both the semicolon and omitting the parenthesis would have fixed the issue alone).
Solution 2:
Problem is here:
(!_.isNull(foo.bar)?foo.bar = true:"");
That statement makes no sense, and I don't think you can assign a property inside the inline if statement. I also don't know why you're trying to overwrite 123
with true
.
Be that as it may, what you seem to be trying to do should be accomplishable by this:
foo.bar = (!_.isNull(foo.bar) ? true : "");
Post a Comment for "Nodejs Object Declaration And Immediate Shorthand If Statement Crashes The App"