Why JavaScript function's toString method is called many times when debugging step by step in Chrome DevTool?

Viewed 75

Test environment:

  • MacOS v10.14.6;
  • Chrome 89.0.4389.82

Question description:

I added a breakpoint in toString method of a function and debug it step by step, I see that the toString method is called when I step to the next line.

It is a little hard to describe it in language, please watch the screen recording:Video

Why?

Code

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    function fn() { }

    fn.toString = function () {
      debugger;
      console.log('toString called');
      const a = 'a';
      return a;
    };

    fn.toString();
  </script>
</body>

</html>
1 Answers

It's just like that when using some IDE to debug a program. The dev tool shows the value of a variable by calling its toString function. When I am debugging a Java program in IDEA, it also works like that.

Related