Chrome JavaScript developer console: Is it possible to call console.log() without a newline?

I'd like to use console.log() to log messages without appending a new line after each call to console.log(). Is this possible?

Answers:

Answer

No, it's not possible. You'll have to keep a string and concatenate if you want it all in one line, or put your output elsewhere (say, another window).

Answer

In NodeJS you can use process.stdout.write and you can add '\n' if you want.

console.log(msg) is equivalent to process.stdout.write(msg + '\n').

Answer

You can put as many things in arguments as you'd like:

console.log('hi','these','words','will','be','separated','by','spaces',window,document)

You'll get all that output on one line with the object references inline and you can then drop down their inspectors from there.

Answer

Yes, it's possible (check out the demo below) -- by implementing your own virtual console on top of the native browser console, then syncing it to the real one.

This is much easier than it sounds:

  1. maintain a display buffer (e.g. an array of strings representing one line each)
  2. call console.clear() before writing to erase any previous contents
  3. call console.log() (or warn, error, etc) to fill the console with the contents from your display buffer

Actually, I've been doing this for some time now. A short, rudimentary implementation of the idea would be something along the following lines, but still capable of animating the console contents:

// =================================================
// Rudimentary implementation of a virtual console.
// =================================================

var virtualConsole = {
    lines: [],
    currentLine: 0,
    log: function (msg, appendToCurrentLine) {
        if (!appendToCurrentLine) virtualConsole.currentLine++;
      
        if (appendToCurrentLine && virtualConsole.lines[virtualConsole.currentLine]) {
            virtualConsole.lines[virtualConsole.currentLine] += msg;
        } else {
            virtualConsole.lines[virtualConsole.currentLine] = msg;
        }
        
        console.clear();
        
        virtualConsole.lines.forEach(function (line) {
            console.log(line);
        });
    },
    clear: function () {
        console.clear();
        virtualConsole.currentLine = 0;
    }
}

// =================================================
// Little demo to demonstrate how it looks.
// =================================================

// Write an initial console entry.
virtualConsole.log("Loading");

// Append to last line a few times.
var loadIndicatorInterval = setInterval(function () {
    virtualConsole.log(".", true); // <- Append.
}, 500);

// Write a new line.
setTimeout(function () {
    clearInterval(loadIndicatorInterval);
    virtualConsole.log("Finished."); // <- New line.
}, 8000);

It sure has its drawbacks when mixing with direct console interaction, and can definitely look ugly -- but it certainly has its valid uses, which you couldn't achieve without it.

Answer

The short answer is no.

But

If your use-case involves attempting to log perpetually changing data while avoiding console-bloat, then one way to achieve this (in certain browsers) would be to use console.clear() before each output.

function writeSingleLine (msg) {

  console.clear();
  console.log(msg);

}

writeSingleLine('this');
setTimeout( function () { writeSingleLine('is'); }, 1000);
setTimeout( function () { writeSingleLine('a'); }, 2000);
setTimeout( function () { writeSingleLine('hack'); }, 3000);

Note that this would probably break any other logging functionality that was taking place within your application.

Disclaimer: I would class this as a hack.

Answer

Something about @shennan idea:

function init(poolSize) {
      var pool = [];
      console._log = console.log;
      console.log = function log() {
        pool.push(arguments);
        while (pool.length > poolSize) pool.shift();
    
        draw();
      }
      console.toLast = function toLast() {
        while (pool.length > poolSize) pool.shift();
        var last = pool.pop() || [];
        for (var a = 0; a < arguments.length; a++) {
            last[last.length++] = arguments[a];
        }
        pool.push(last);
    
        draw();
      }
      function draw() {
        console.clear();
        for(var i = 0; i < pool.length; i++)
          console._log.apply(console, pool[i]);
      }
    }
    
    function restore() {
      console.log = console._log;
      delete console._log;
      delete console.toLast;
    }
    
    init(3);
    console.log(1);
    console.log(2);
    console.log(3);
    console.log(4);    // 1 will disappeared here
    console.toLast(5); // 5 will go to row with 4
    restore();

Answer

collect your output in an array and then use join function with a preferred separator

function echo(name, num){
    var ar= [];
    for(var i =0;i<num;i++){
        ar.push(name);
    }
    console.log(ar.join(', '));
}

echo("apple",3)

check also Array.prototype.join() for mode details

var elements = ['Fire', 'Wind', 'Rain'];

console.log(elements.join());
// expected output: Fire,Wind,Rain

console.log(elements.join(''));
// expected output: FireWindRain

console.log(elements.join('-'));
// expected output: Fire-Wind-Rain
Answer

If your only purpose to stop printing on many lines, One way is to group the values if you don't want them to fill your complete console

P.S.:- See you browser console for output

let arr = new Array(10).fill(0)


console.groupCollapsed('index')

arr.forEach((val,index) => {
  console.log(index)
})

console.groupEnd()

console.group

console.groupCollapsed

Answer

You can use a spread operator to display output in the single line. The new feature of javascript ES6. see below example

   for(let i = 1; i<=10; i++){
        let arrData = [];
        for(let j = 1; j<= 10; j++){
            arrData.push(j+"X"+i+"="+(j*i));
        }
        console.log(...arrData);
    }

That will print 1 to 10 table in single line.

Answer
// Source code for printing 2d array
window.onload = function () {
    var A = [[1, 2], [3, 4]];
    Print(A);
}

function Print(A) {
    var rows = A.length;
    var cols = A[0].length;
    var line = "";
    for (var r = 0; r < rows; r++) {
        line = "";
        for (var c = 0; c < cols; c++) {
            line += A[r][c] + " ";
        }
        console.log(line);
    }
}
Answer

if you want for example console log array elements without a newline you can do like this

const arr = [1,2,3,4,5];

Array.prototype.log = (sep='') => {
    let res = '';
    for(let j=0; j<this.lengthl j++){
        res += this[j];
        res += sep;
    }
    console.log(res);
}

// console loging

arr.log(sep=' '); // result is: 1 2 3 4 5 

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.