Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant Javascript code for checking undefined values

So I have a callback function which provides a json object:

function(object){
    var data=object.packet.link.ip.tcp.data;
    console.log(data.toString());
}

The problem I have is that any of packet/link/ip/tcp/data can be "undefined" - my node.js program falls over every time it hits an undefined variable.

I tried putting the declaration of "data" inside try/catch, however I keep getting "undefined" errors - my guess is that I'd need to put object/object.packet/object.packet.link/object.packet.link.ip/etc. in try/catch.

So, I found some elegant coffeescript:

if object?.packet?.link?.ip?.tcp?.data? then doStuff()

which compiles to:

var _ref, _ref1, _ref2, _ref3;

if ((typeof object !== "undefined" && object !== null ? (_ref = object.packet) != null ? (_ref1 = _ref.link) != null ? (_ref2 = _ref1.ip) != null ? (_ref3 = _ref2.tcp) != null ? _ref3.data : void 0 : void 0 : void 0 : void 0 : void 0) != null) {
       //doStuff:
       var data = object.packet.link.ip.tcp.data;
       console.log(data.toString());
}

Yuck!

Now it works perfectly, but I was just wondering if there's a more elegant (readable) way of doing this in pure Javascript?

like image 572
Eamorr Avatar asked Jun 30 '26 13:06

Eamorr


1 Answers

You can do

["packet", "link", "ip", "tcp", "data"]
  .reduce(function (m, i) { if (m) return m[i]; }, object);

You could move the reduce into a function and have get(object, "packet", "link", "ip", "tcp", "data"). It can be pretty, although a simple && solution might be more sensible.

like image 163
Karolis Juodelė Avatar answered Jul 03 '26 03:07

Karolis Juodelė



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!