loading...

What's the difference between an Object's method and a key with a function value?

calin92540842 profile image PDS OWNER CALIN (Calin Baenen) ・1 min read

So, I was wondering what the difference between an Object method

{
    methodName(param) {
        return 3;
    }
};

and a key with a function value

{
    methodName: function methodName(param) {
        return 3;
    }
}

Thanks!
Cheers!

Discussion

markdown guide
 

Technically, there is no difference.

I would argue, though, that the longer format gives you more opportunity to give semantic names to your functions that might differ from the object key they are being associated with, which aids code maintainers.

For example, a very basic implementation of an interface in JavaScript is to have objects with the same keys but different values. The longer format gives you the flexibility to provide a function name that means more to the reader than the more generic name of the object key:

var motorcycle = {
  powerOn: function kickStart() { ... }
};

var zipcar = {
  powerOn: function useKeyCard() { ... }
};

var horse = {
  powerOn: function feedAndPet() { ... }
};

Obviously this example is pretty contrived. But I hope the value is clear regardless: flexibility to have a function name that does not match the object key gives you power over the reader, and the opportunity to facilitate code maintenance by better communicating your intent.

 

If there is a difference, its probably some obscure with prototypes/this ;)
You can try to dig it out in You dont know JS but i wouldnt bother until it breaks.

 
 

There's no difference. The first one is a shorthand added in ES2015, but they do exactly the same thing.

Not to be confused with the following though, which is different. Sigh, JS.

{
  methodName: param => {
    return 3;
  }
}
 

Thanks! It really heps! Would you say it's "safer" to use the longer version, though?

 

The shorthand version is supported in every modern browser, but I think it could trip up some old versions + Internet Explorer, so it depends if you're expecting people with legacy browsers to visit your site. Personally I wouldn't worry too much about it.

Also, I think if you're using frameworks like React, Angular or anything that uses a transpiler like Babel it will be able to automatically convert to the older version during the build process.