Skip to content

Instantly share code, notes, and snippets.

@zachlysobey
Last active August 7, 2023 01:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zachlysobey/40d3536eb0c3afe1788f808b7da2b2a0 to your computer and use it in GitHub Desktop.
Save zachlysobey/40d3536eb0c3afe1788f808b7da2b2a0 to your computer and use it in GitHub Desktop.
Thoguhts on JS object shorthand vs longhand

I appreciate the brevity of the shorthand 🤷

const foo = () => ({ a: 1, b: 2 });

compare that to:

const foo = () => {
  return { a: 1, b: 2 };
};

But, I don't think the long-hand ever really bothers me, and can have some real benefits.

Like if something has to change in the future, it makes diffs cleaner.

contrived example:

- const someFn = () => ({
+ const someFn = () => {
-   foo: "bar"
+   const bar = "bar";
+   return {
+     foo: bar
+   };
- });
+ };

vs

  const someFn = () => {
+   const bar = "bar";
    return {
-     foo: "bar"
+     foo: bar
    };
  };

And its easier to throw debugging stuff in, etc...

  const someFn = () => {
+   console.log('debugging is fun');
    return {
     foo: "bar"
    };
  };
@mmaycock
Copy link

mmaycock commented Aug 7, 2023

The diffs are less about the shorthand / longhand and more about style.

const foo () => ({
  a: 1,
  b: 2
});

My only preference for the shorthand is that it's a single expression vs. a series of statements and is thus a simpler grammatical structure (as expressions are statements [in most languages at least that have both]). Adding in debugging info isn't that difficult just minimal work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment