Not exactly a one-liner, but my neatest quick trick: If you have a one-liner arrow function, but you want to log out the parameter, you don't need to give it curly braces and an explicit return.
Go from this:
const addFortyTwo = number => number + 42
To this:
const addFortyTwo = number => console.log(number) || number + 42
It works because console.log returns undefined, which is falsey, so the expression evaluates to the other side of the || 'or' operator, but only after running the console.log. Neat!
I did say it's more obnoxious to use the comma operator. I do not recommend it, I just wanted to offer an alternative for those that might like the syntax better. There are some cases where the comma operator is more useful / easier to use, but I can't say I recommend using it in general as it creates code that's easier to forget about, which might create some unintentional side effects.
I also agree with this, and I don't particularly like that syntax either. Usually it's something you can do for dev real quick and delete it before you commit, though.
I use this all the time but as a condition on a breakpoint. Because it’s falsey, it won’t stop at the breakpoint, but you get console log statements without altering the code. Super handy for dealing with more time sensitive code or where it’s too much work to alter the source.
Due to the same fact, if you want to log a variable at any given point, you can just add a conditional breakpoint with console.log(variable) and it'll log without stopping execution
130
u/Earhacker Mar 18 '19 edited Mar 19 '19
Not exactly a one-liner, but my neatest quick trick: If you have a one-liner arrow function, but you want to log out the parameter, you don't need to give it curly braces and an explicit return.
Go from this:
To this:
It works because
console.logreturnsundefined, which is falsey, so the expression evaluates to the other side of the||'or' operator, but only after running theconsole.log. Neat!