DEV Community

Discussion on: Prevent Object Retrieval TypeError with &&

Collapse
 
moopet profile image
Ben Sinclair

This is something you see a lot when stringing shell commands together.

mkdir my_directory && cd my_directory || exit(1)

This way of using && before running a function (or command) and calling it a "guard operator" makes it seem like it's not what it actually is (an expression).

It gets a little odd when you try to do things that seem to make sense on the face of it, like use an assignment instead of a final expression:

foo = {};

foo.bar || "hello";
// "hello"

console.log(foo.thisworks = "hello")
// "hello"

foo.bar || foo.bar = "hello";
// Invalid left-hand side in assignment

foo.bar && foo.baz = "hello";
// Invalid left-hand side in assignment

foo.bar && (foo.baz = "hello");
// "hello"

And it can be tempting to string too many of them together and make quite a confusing line.

I prefer to be explicit, and to dive out if the condition isn't met:

function do_the_foo(foo) {
  if (typeof foo.bar == "undefined") {
    // handle stuff or...
    return;
  }

  // continue...
  console.log(foo.bar.baz);
}
Collapse
 
tdubs profile image
Thom W

Maybe 'Gate' would be a better word?