How to console log *without* newline in JS

Awesome JS one-liners, console.log without \n, and more

Recommended

  • Techpresso: a daily rundown of what’s happening in tech and what you shouldn’t miss. Read by professionals at Google, Apple, and OpenAI. Check it out

  • GPTE AI: Discover over 5,000 new AI tools for productivity, design, content creation, and more. Check it out

Here's something most JavaScript developers don't know:

You can shorten any piece of code into a single line.

With one-liners I went from 17 imperative lines:

// ❌ 17 lines
function extractRedirects(str) {
  let lines = str.split('\n');
  let sourceDestinationList = [];

  for (let line of lines) {
    let sourceDestination = line.split(' ');
    let source = sourceDestination[2];
    let destination = sourceDestination[3];
    let redirectObj = {
      source: source,
      destination: destination,
      permanent: true,
    };
    sourceDestinationList.push(redirectObj);
  }
  
  return sourceDestinationList;
}

To a single functional statement:

// ✅ 1 line -- formatted
const extractRedirects = (str) =>
  str
    .split('\n')
    .map((line) => line.split(' '))
    .map(([, , source, destination]) => ({
      source,
      destination,
      permanent: true,
    }));

The second is so much cleaner and elegant -- you can clearly see how the data beautifully flows from input to output with no breaks.

Let's look at 10 unconventional JS one-liners that push you to the limits of what's possible with JavaScript.

What do you make of this:

// ✅ Standard Fisher-Yates shuffle, functional version
const shuffleArray = (arr) =>
  [...Array(arr.length)]
    .map((_, i) => Math.floor(Math.random() * (i + 1)))
    .reduce(
      (shuffled, r, i) =>
        shuffled.map((num, j) =>
          j === i ? shuffled[r] : j === r ? shuffled[i] : num
        ),
      arr
    );

// [ 2, 4, 1, 3, 5 ] (varies)
console.log(shuffleArray([1, 2, 3, 4, 5]));

The most complex thing for me was figuring out the immutable no-variable version of the swap — and reduce() has a way of making your head spin.

Then there's this too:

This is a little-known way to console log without newline that many developers have never used.

Let's say we need to log in a loop like this:

for (let i = 1; i <= 5; i++) {
  // print number without newline
}
// Output: 1 2 3 4 5

Unfortunately normal console log doesn’t work.

So what do we do?

What we do: is process.stdout.write:

How is process.stdout.write different from console.log?

Well first of all, console.log is process.stdout.write!

stdout is the fundamental way every CLI program logs output to the console.

That’s what it uses at its core:

Thanks for taking the time to read today’s issue.

Don’t let the bugs byte,
Tari Ibaba