0

I have a Javascript function written as follows:

function refresh(selection, xPath, yPath, xAnnotationSelection, yAnnotationSelection) {
      var coords = selection.node().__coord__;
      ...
}

The function is being called sometimes, with the variable selection not having been set yet, which causes the following exception to be thrown:

Uncaught TypeError: Cannot read property 'coord' of null

What is a better way to write the statement so that it first checks to make sure that selection is not null, before attempting to call a method on it?

Pseudocode:

var coords = (selection ? ((selection.node ? selection.node().__coord__: null) : null);
Homunculus Reticulli
  • 65,167
  • 81
  • 216
  • 341
  • Your pseudocode should work if you change selection.node to selection.node() – Barkha Aug 25 '19 at 11:11
  • did you meaning you want at first check if the selection then do in it not found it should be default value null – Mohammed Al-Reai Aug 25 '19 at 11:11
  • coords = selection ? (selection.node() ? selection.node().__coord__: null) : null; – Barkha Aug 25 '19 at 11:13
  • 1
    Use a ternary operator only for simple to read expressions. For anything else go with regular `if` statements. The goal of good code is not to create fancy one-liners, but to create easily understandable and maintainable code. – t.niese Aug 25 '19 at 11:18
  • or can be best coords = selection ? (selection.node() ? selection.node().__coord__: null) : null; or simple this code const section2= selection.node()?selection.node().__coord__: null; const coords=selection?section2:null or can used as if statment const icoords=null; if(selection&&selection.node()){ icoords=selection.node().__coord__ } – Mohammed Al-Reai Aug 25 '19 at 11:23

2 Answers2

0

You can write -:

var coords = selection && selection.node && selection.node().__coord__;
Abhisar Tripathi
  • 1,569
  • 10
  • 21
-1

I think the best way for your function is:

function refresh(selection, xPath, yPath, xAnnotationSelection, yAnnotationSelection) {
  const node = selection && selection.node();
  if (!node) {
    return null;
  }
  var coords = node.__coord__;
  ...
}
Maxim Pyshko
  • 551
  • 4
  • 14