Quick Tip to Auto Labelling Variable Logs

I just wanted to share a quick tip I learned on Twitter a while ago. It was about how you can wrap curly braces around a variable in your console.log statements to transform it into an object and have the variable name automatically prefixed.

The trick is the so-called Destructuring Assignment. When used in the context of objects, it creates a property in the object with the same value and name (!) as the variable. We create an anonymous object with properties for the variables we want to log. This way, we print out the property name with their respective values.

const foo = 'bar', bar = 42;
console.log({ foo, bar }); // Object { foo: "bar", bar: 42 }

This helps to track the values in the console output easily with label-prefixing out of the box. It ditches the need to add descriptive strings like 'foo: ', foo.