#13

Easy console.log in Arrow Functions

2019-08-23

TAGS: javascript

Generally if I want to log out what's getting passed into an arrow function like this:

const newNames = names.map( name => doThing(name) )

I have to add brackets and a return like this:

const newNames = names.map( name =>  {
  console.log(name);
  return doThing(name);
})

But because console.log()'s value is void, the || (OR) operator will run the function, and because it's falsey, return the second thing, like this:

const newNames = names.map( name => console.log(name) || doThing(name) )

TypeScript yells at you saying console.log() will never resolve as true. But we're not shipping the code, just debugging. It works just fine for that.


Thanks to my coworker Brendan for showing me this trick.