0

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.

rgettman
  • 176,041
  • 30
  • 275
  • 357

2 Answers2

2

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

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
-1

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 : "");
Paul
  • 35,689
  • 11
  • 93
  • 122
  • 1
    This is just a very simple example of the issue at hand, and there is no reason why you cannot assign a variable inside an if. I am aware I can achieve the same outcome with the if you have described the issue is with the object declaration not being recognised in the first place. you could add another varliable to the object and assign a different value to it and still have the same issue. – Interbred Monkey Nov 25 '14 at 16:26