Menu

Log inside a loop without touching the code
📰

Log inside a loop without touching the code

DEV Community: javascript·JSLab·about 1 month ago
#2upheQv5
#devtojavascript#devto#dev#loop#line
Long article (761 words) — no AI summary yet.
Reading 0:00
15s threshold

Loops are where console.log goes to multiply. One log per pass is fine for 8 passes and useless for 8,000. Here are the techniques I reach for, from "edit the code" to "don't touch it at all".

The loop we'll debug finds spikes in a list of readings:

const readings = [ 12 , 15 , 11 , 40 , 14 , 13 , 90 , 12 ]; const spikes = [];

for ( let i = 0 ; i < readings . length ; i ++ ) { const delta = readings [ i ] - ( readings [ i - 1 ] ?? readings [ i ]); if ( delta > 20 ) spikes . push ( i ); }

spikes ; // [3, 6]

Enter fullscreen mode

Exit fullscreen mode

1. Log only what matters

Logging every pass buries the answer. Log the passes you care about:

for ( let i = 0 ; i < readings . length ; i ++ ) { const delta = readings [ i ] - ( readings [ i - 1 ] ?? readings [ i ]); if ( delta > 20 ) console . log ({ i , delta }); if ( delta > 20 ) spikes .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.