How to log easily an arrow function in JavaScript and TypeScript
How to debug JavasScript and TypeScript without touching (too much) the existing code

Logging in JavaScript is pretty easy, and there a lot of editor helping the debug phase of your code, you can set a breakpoint or even better a conditional breakpoints in Chrome for example.
But sometimes you still want to log a parameter of a specific function arrow function. The problem is that the common approach requires to rewrite a part of your code as an arrow function implies that only the return value is inside the parentheses. Other instruction or assignment will break your code.
So for example if I have a function like:
const doubleValue= (x) => (2*x)
If I want to log the value of x before returning the value I need to adjust the code like:
The above example is a really trivial one, but what about something more specific, like logging a single property of an object?
const f = ({a,b,c}) => { console.log(a); return {a,b,c});
And what about another scenario like a functional component in React JS, in which the you want to inspect a certain prop and you have to fight again multiple curly braces?
Well I found a less painfull way that doesn’t involve any rewriting, just adding the console.log in the right way, well is a bit tricky to be honest
For the example aboves:
const doubleValue= (x) => !console.log(x) && (2*x)const f1 = ({ a, b, c }) => !console.log(a) && { a, b, c };
And in a React JS scenario:
const UserComponent = (props) => (
<h1>{`Hello ${props.name} ${props.surname}`}</h1>
);const UserComponentWithLog = (props) =>
console.log(props) || <h1>{`Hello ${props.name} ${props.surname}`}</h1>;
So where is the magic? In order to let the normal flow of the execution going ahead, you need to add something always true, console.log() is a void instruction that when negated in js becomes truthy.
In the React JS example it is also very easy to chain a conditional rendering with the same trick without impacting other parts of the code.
The same examples in Codepen and in Codesanbox
Update: What about TypeScript?
In TypeScript the same condition will throw an error at compile time, as void cannot be together with a boolean. But you can easily add a small helper function like:
const cl = (o: any) => { console.log(o); return true; }
Then you can use it inside your code without changing the structure of your statements:
if (cl(data) && data) {
return <div>hello with data </div>
}
And this can be also used inside conditional rendering
{cl(props) && translateTitle(props.title)}