React Native

One cool trick using this obscure JavaScript syntax

What are we talking about? What is the comma operator?

Do you know the ++code>(a, b); ++/code> syntax in JS?

You might have seen it if you read minified code - our favorite Sunday activity. I've always wondered about its purpose, and I've finally found a cool use case!

This is called the comma operator. You can find it in many languages, in multiple forms.

Here in our case, ++code>(a, b); ++/code> means "evaluate a, evaluate b, then return b.". The return value of a is discarded.

So, if I do ++code>const croute = (a, b); ++/code>, croute is equal to b, and I would still have computed a (…to no avail, unless there is a side effect in computing a).

When can I use the comma operator?

Well, we found ourselves wanting to debug a very complex expression where we didn't even know where the calling function was. We didn't know where to put our console.log.

Note: our debugger wasn't working at that moment. Do as your parents told you, use a debugger if you can!

But thanks to this syntax, we can console.log any value in the middle of any expression. It's enough that, in our notation above, a is console.log(b) and b remains b. Thus, ++code>(console.log(b), b) <=> b ++/code>

So, if I have this:
++pre> ++code> const myObject = {
 a: 123,
 b: 456,
 c: {
   d: myComplicatedValue,
 }
} ++/code>++/pre>


And we transform it into this:
++pre> ++code> const myObject = {
 a: 123,
 b: 456,
 c: {
   d: (console.log(myComplicatedValue), myComplicatedValue),
 }
} ++/code>++/pre>

Then, everything is equivalent, except that we have a console log in the middle of our expression 🙂

The example above looks straightforward, but you might encounter this kind of craziness on minified code:
++pre> ++code>// imagine an expression full of side effects 🤯
// there's no room for classic statements in-between the elements of our array
// as our value A changes for each element that we add in the array and
// we'd like to know what happens in the middle of it
const arrayFullOfMutations = [
 functionThatMutatesA(A),
 // <--- what does A look like here???
 functionThatMutatesA(A),
];

// well, now you can easily print out anything
// anywhere in the middle of it using the (a, b) syntax
const arrayFullOfMutations = [
 functionThatMutatesA(A),
 functionThatMutatesA((console.log('A before it changes for the 2nd time', A), A),
];
console.log('A is not the same anymore', A)++/code>++/pre>



I’m sure you can find many other use-cases. However, I would only keep this syntax for debugging and one-shot try-outs. I wouldn’t merge code that contains this as it wouldn’t be very readable, especially since it is not very widespread!

I hope it will become handy. If it doesn’t, at least you might have learned what ++code>(a, b); ++/code> actually does 🙂

Développeur mobile ?

Rejoins nos équipes