nodejs object declaration and immediate shorthand if statement crashes the app

303 views Asked by At

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.

2

There are 2 answers

1
Bergi On BEST ANSWER

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).

1
Paul On

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 : "");