1

Just wondering, having the following simple code:

var object1 = {
    name: function (){
        return 'myName';
    },
    surname: function (){
        return 'mySurname';
    }
};

Why does JS returns function() in this case object1.name ?

Why does JS returns the expected result myName if I call object1.name() ?

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Jackie Chan
  • 2,654
  • 6
  • 35
  • 70

3 Answers3

2
  1. Referencing name returns what name is–in this case, a function.
  2. Calling name by appending (), i.e., name(), returns a value–the string "myName".

My answer to When do I use parenthesis and when do I not? provides more details.

Community
  • 1
  • 1
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
1
object1.name;//Returns the function declaration
object1.name();//Calls the function and returns its value

It works like the following code:

var myFn = function(){
    return "This is the return value of this function";
}
alert(myFn);//Alerts the myFn function's declaration
alert(myFn());//Alerts "This is the return value of this function"
Danilo Valente
  • 11,270
  • 8
  • 53
  • 67
1

because in object1.name you are calling the function declaration

and in object1.name() you are calling the function

Ibu
  • 42,752
  • 13
  • 76
  • 103