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?
2 Answers 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.
1 Comment
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 =>
8 Comments
hello without () ?console.log() calls toString() internally to get the string to display.toString.
nameandcodeproperty?