sapna koramagiri
sapna koramagiri

Reputation: 81

Why function variable (when logged in console) does not show the whole function body?

I would like to know why function variable (when logged in console) does not show the whole function body but toString() method does.

function person(name) {
    this.f_name = name;

    return function print_name (){
            alert("Your Name Is: " + this.f_name);
        }
  }

var myfunc = person('James');

  console.log(myfunc); //-> function print_name()

  console.log(myfunc.toString()); // ->"function print_name(){
        alert("Your Name Is: " + this.f_name);
    }"

Upvotes: 1

Views: 98

Answers (1)

SidOfc
SidOfc

Reputation: 4584

Everything you console.log that can't just be printed gets it's respective toString method called to still be able to represent / summary the most important details about the function.

As you can read here: MDN - and specifically this quote:

the toString method returns a string representation of the object in the form of a function declaration. That is, toString decompiles the function, and the string returned includes the function keyword, the argument list, curly braces, and the source of the function body [1].

This basically says you don't need to know the internals to debug since you can look at the source for that (either in the devtools or in your editor) so it doesn't bother printing everything - just that which is required / convenient for the programmer to know at that time.

[1] - I don't actually know why this line is there or I'm misunderstanding. (As pointed out by @deceze in the comments below)

I ran the following code in the dev tools of some browsers to compare:

console.log(function(a, b) { return a + b; });

Output:

  • Firefox: function () - w/o arguments but clickable to see more info
  • Chrome: function (a, b) { return a + b } w/ arguments, clicking it takes you to a pane in the devtools with the source of the function
  • Safari: function (a, b) { return a + b; }, w/ arguments, clicking does nothing

As I'm on a Mac I can't test this in IE but the outputs are interesting. It's more of a developer's preference as to which browser he/she develops in since this is just a dev API and not something that should be consistent cross-browser.

Upvotes: 1

Related Questions