This page looks best with JavaScript enabled

Console.log function for easier debugging

 ·   ·  ☕ 2 min read

Encapsulate a console.log() in a function and use it anywhere - even within the most complex expressions.

The most typical console.log -

1
2
console.log("hello world");
// hello world

Change it to -

1
2
3
4
5
6
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.

1
2
3
4
5
6
7
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.

1
2
3
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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things