Encapsulate a console.log() in a function and use it anywhere - even within the most complex expressions.
The most typical console.log -
console.log("hello world");
// hello world
Change it to -
function logThis(expr) {
console.log(expr);
return expr;
}
logThis("hello world"); // hello
Why the circus?
Well, consider you are debugging this really serious planet array marked for destruction.
const planets = [
{ name: "mercury", position: 1 },
{ name: "venus", position: 2 },
{ name: "earth", position: 3 }
];
console.log(planets.sort().filter(planet => planet.position == 3));
Sure, you can unchain the chain and debug.
console.log(planets);
console.log(planets.sort());
console.log(planets.sort().filter(planet => planet.position == 3));
But, there is no joy in the above code (and in the destruction task I might add). Is there?
Let’s try the encapsulated console.
function logThis(expr) {
console.log(expr);
return expr;
}
const planets = [
{ name: "mercury", position: 1 },
{ name: "venus", position: 2 },
{ name: "earth", position: 3 }
];
console.log(
planets
.sort(x => logThis(x))
.filter(planet => logThis(logThis(planet).position == 3))
);
/*
{ name: 'venus', position: 2 }
{ name: 'earth', position: 3 }
{ name: 'mercury', position: 1 }
false
{ name: 'venus', position: 2 }
false
{ name: 'earth', position: 3 }
true
[ { name: 'earth', position: 3 } ]
*/
Since we just do a print and return loop within the encapsulation, it is quite easy to include the console statement anywhere.