1

How to print some literal in console with console.log (or another command) command in same line?

For example:

print 1;
print 2;
print 3;

Console output: 123

3
  • 1
    Totally unclear what you're trying to achieve. Commented Dec 15, 2017 at 7:59
  • 1
    This is simple not possible or for at least in the browsers I use (chrome, ff, edge, ie). The closest possibility would be console.log(1, 2, 3) Commented Dec 15, 2017 at 8:02
  • Maybe there is some another command... Commented Dec 15, 2017 at 8:31

1 Answer 1

1

Assuming I understood you correctly, you want a JavaScript equivalent of C#'s Console.Write, that appends (a) character(s) to the last line.

That's not possible.

The moment something is logged to the console, you no longer have access to it. You can't "append" to a logged line, you can't change it.


That said, you could write a wrapper that sortof emulates this behavior:

let logTimeout;        // Keep track of the pending timeout
let logArguments = []; // Keep track of the passed loggable arguments


function log(...args) {
  if (logTimeout) {
    logTimeout = clearTimeout(logTimeout);  // Reset the timeout if it's pending.
  }

  logArguments = logArguments.concat(args); // Add the new arguments.
  
  logTimeout = setTimeout(() => {           // Log all arguments after a short delay.
    console.log(...logArguments);
    logArguments.length = 0;
  });
}

log(1);
log(2);
log(3);
log("foo");
log("bar");
log({crazy: "stuff"});

setTimeout(() => {
  log(4);
  log(5);
  log(6);
  log("baz");
  log("woo");
  log([{crazier: "stuff"}]);
}, 500);

Just note that this logger is asynchronous. This means your code that calls log will run to completion before something is actually logged.

Sign up to request clarification or add additional context in comments.

3 Comments

Tell me please, the "..." in arguments is the new feature in ES6?
Yes it is, it's the spread operator. It's quite nifty!
Cool. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.