4 ms·
A small extra trick: If you use arrow functions without a body you can log and fallback to the original statement. Example starting point, you're wondering wh
by Griffinsauce 5y ago
A small extra trick:
If you use arrow functions without a body you can log and fallback to the original statement.
Example starting point, you're wondering what message is.
```
const upperCase = (message) =>
message.upperCase()
```
Don't add a body, just log and continue:
```
const upperCase = (message) =>
console.log(message) ||
message.upperCase()
```
- Stratoscope 5y agoThat will work, because console.log() returns undefined. It is a bit subtle for my taste, though. My suggestion for clarity is to go ahead and make the function have a body with {}: const upperCase = (message) => { console.log(message); return message.upperCase(); }; Of course you may disagree, but no argument there, as I said it's a matter of taste. (BTW backticks, either triple or single, do not work on HN. Indent by two spaces if you want code formatting.)
- Griffinsauce 5y agoYeah, I'm working on the assumption that this code is not committed but for a quick debug. Any code that is shared shouldn't rely on that, I agree. Thanks for the tip!
- genezeta 5y agoSince most of the times I want "a quick debug" I'm already on my browser and quite probably with the dev tools already open, I prefer right-clicking on a line and using "Add Log" (in Firefox) or "Add logpoint" (in Chrome-based browsers). It avoids having to modify the source and then clean it up when I'm done.
- wonnage 5y agoYou can also use the comma operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe... `const upperCase = (message) => (console.log(message), message.upperCase())` The function body needs to be in parens. Maybe not the most useful for this case, but I've used this when setting logpoints in Chrome to log a variable and save it to a global for further inspection.
- skywal_l 5y agoYes, useful when trying to debug functional style chaining: const result = array .map(someFunction) .filter(someOtherFunction) .map(x => (console.log(x), x)) // debug here .map(stillAnotherFunction);
- Cthulhu_ 5y agoI should remember that one, I use a lot of console.log debugging still.
- Accacin 5y agoI do something similar in React too: const foo = () => console.log && <Something /> That stops the body rendering, and you can use '||' if you want the body and the log.