Utsav Prasad
Utsav Prasad

Reputation: 78

Why console.log displays function definition when called with function name

Here is something that I executed

function c(){
  return 2+3;
}
console.log(c);
console.log(c());

I understand what happens behind the scene when console.log(c()) is executed but when it comes to console.log(c) I am little confused.

For console.log(c) I get the output:

f c(){
  return 2+3;
}

What is happening here?

Does c store the whole function definition into it or it stores the address of the of the function definition?

If it stores the whole function definition then in what form does it store? Is it stored as string?

Or if it stores the address then how? Because when the process run the memory contains the machine instructions not the JavaScript program. Then where did it come from?

Upvotes: 1

Views: 781

Answers (2)

Scott Czerneda
Scott Czerneda

Reputation: 1

What's stored in memory is the source code of the function. c is a reference (address) to the location in memory where that source code is stored. When the code runs, only then is it interpreted into machine instructions. I believe even engines like V8 still interpret the code at run time (although someone more knowledgable on those types of engines can correct me here if I'm wrong).

As Yousaf said in their answer, calling any object by its name alone automatically invokes the toString() method.

I don't know that it's possible in JavaScript to access what that the exact address is, like how you could in a lower-level language like C.

Upvotes: 0

Byvad
Byvad

Reputation: 46

A function is like a book, each one has a unique title and they are stored somewhere in your storage. So when you say "give me the function with name 'c' please" it is going to give you the whole function, not just the name. Just like when you're in a library and you ask for a specific book, they are going to give you the whole book and not just the front page with the title on it.

if you only want to print the name you just say console.log(c.name)

Hope this helped :)

Upvotes: 2

Related Questions