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
  • 156,572
  • 25
  • 250
  • 300
Jackie Chan
  • 2,596
  • 6
  • 34
  • 68

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
  • 156,572
  • 25
  • 250
  • 300
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,037
  • 8
  • 52
  • 66
1

because in object1.name you are calling the function declaration

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

Ibu
  • 41,298
  • 13
  • 73
  • 100