Is there an alternative to console.log() which lets you print out and update a single line instead of spamming the console?

Viewed 623

I am looking for a way to print out a given variable f.ex. the i of a for-loop for each iteration, without it resulting in the entire console being filled with new lines of new values. Is there a console. method for just printing one line, and updating that as we go?

I realise that you could do this by implementing a text-field in your program which you change the with each iteration, but if there is a way of doing this in the console it would be a bit easier (and perhaps quicker? although I am really not sure about that). Thanks in advance.

If there is still confusion about what im asking, what i want is my console to print out: "i = " i once, and then update the i in that one line, instead of:

i=1
i=2
i=3
1=4
.
.
.

which gets really messy as you go. For the exact example of the i in a for loop, you could get this value from just console.log()'ing the same thing for each iteration, and a number will pop up beside it (in firefox anyway), but i would like to be able to do this with some more useful information.

2 Answers

Option 1: use console.groupCollapsed() and console.groupEnd():

    console.groupCollapsed();
    for (let i = 0; i < 100; i+= 1) { console.log(`i = ${i}`) }
    console.groupEnd();

Option 2: set the values in an array or a string and log the var when the iterations finish:

    let valuesToLog = [];
    for (let i = 0; i < 100; i+= 1) { valuesToLog.push(`i = ${i}`) }
    // see it as an array
    console.log(valuesToLog);
    // see it as a string, with each value separated by ', '
    console.log(valuesToLog.join(', '));

how about JQuery console.clear()?

$(function(){
    loop_counter();
});

function loop_counter() {
    for (let i = 1; i <= 100; i++){
        console.clear();
        console.log ("i=", i)
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Related