0

I had a question regarding JavaScript Functions. I read Functions as Objects where we can add properties and methods to the functions as well but I notice some strange behavior when I log out the function with the property added. Here is a small example I have taken with object and function.

//Object Example
var obj = {
    firstName: 'John',
    lastName: 'Doe',
};
obj.address = '111 Main St. New York, NY';
console.log(obj); // Object {firstName: "John", lastName: "Doe", address: "111 Main St. New York, NY"}

//Function Example
function myFunction () {
    console.log('Hello World');
}
myFunction.greet = 'Hello JavaScript!';
console.log(myFunction); // function myFunction() { console.log('Hello World');}

As expected the 'greet' property has been added to myFunction but when I log out myFunction I don't the see the property printing out. Why? Where has the property been added? Whereas When I access the property with the dot operator I see the result logging out.

Can someone explain where the property has been added and where it gets stored?

1
  • The property is there, you just cannot see it with console.log. Different browsers will display things differently. Commented Jan 28, 2017 at 21:31

2 Answers 2

1

You could get the own properties with Object.keys of the function.

function myFunction () {
    console.log('Hello World');
}
myFunction.greet = 'Hello JavaScript!';

console.log(Object.keys(myFunction));

Sign up to request clarification or add additional context in comments.

Comments

1

The browser sees that the variable is a function, so when you log out the variable, it tries to print it in the console in a useful way to the developer. Normally we don't look at functions as things that have additional properties, so whatever's implementing console.log doesn't try to show you that information. But the thing you see from console.log isn't really tied to the actual mechanics of the language, it's just there to make things easy to understand for the developer. These properties get stored in the same way, in the same place (RAM) as they do for other objects.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.