DEV Community


Discussion on: Prevent Object Retrieval TypeError with &&

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 = {}; || "hello";
// "hello"

console.log(foo.thisworks = "hello")
// "hello" || = "hello";
// Invalid left-hand side in assignment && foo.baz = "hello";
// Invalid left-hand side in assignment && (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 == "undefined") {
    // handle stuff or...

  // continue...
tdubs profile image
Thom W

Maybe 'Gate' would be a better word?