1
function hello(){
 console.log('Goodbye');
}

is an object. Almost everything in js is object. We have name property on it and its hello, but what about code property? How can I access that? Also, do I have the code inside {} or the whole whats above?

asked Dec 26, 2017 at 8:01
2
  • where is your name and code property? Commented Dec 26, 2017 at 8:02
  • @AnkitAgarwal hello.name Commented Dec 26, 2017 at 8:03

2 Answers 2

2

The code of a function is not in a publicly accessible property. It's stored in an internal [[Code]] property, as specified in Creating Function Objects.

The toString() method of a function will return the entire function definition as a string.

answered Dec 26, 2017 at 8:17
Sign up to request clarification or add additional context in comments.

1 Comment

That is what I need. Thanks. Did not knew about [[Code]]. Not very occasional on the surface of the js code.
2

Also, do I have the code inside {} or the whole whats above?

For your method, use toString

hello.toString()

Demo

function hello(){
 console.log('Goodbye');
}
console.log(hello.toString());

And if you only want to access code between { and }, then (assuming it is not an arrow function)

var code = hello.toString();
code = code.substring( code.indexOf( "{" ) + 1 ); //remove code before first {
code = code.substring( 0, code.lastIndexOf( "}" ) - 1 ); //remove code from last }

If it is an arrow function, then

var hello = () => console.log('Goodbye');
var code = hello.toString();
code = code.substring( code.indexOf( "=>" ) + 2 ); //get the string after =>
answered Dec 26, 2017 at 8:02

8 Comments

Is that the same thing as when I just do hello without () ?
@Learnonhardway Sorry I didn't get do hello without ().
@Learnonhardway console.log() calls toString() internally to get the string to display.
@gurvinder372 Means, getting the code without invoking it.
@Learnonhardway you are not invoking the function, just getting its body by doing toString.
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.