mhdev
mhdev

Reputation: 41

javascript naming a function in an object

Which one should I use between these two, is there one that has an advantage over the other?

// 1st
{ ["test"]() { return 1; } }

// 2nd
{ "test": function () { return 1; } }

Upvotes: 0

Views: 107

Answers (3)

jonatjano
jonatjano

Reputation: 3738

"test": function () { return 1; } is the old way and "test"() { return 1; } the new way with the function keyword being ommited.

Also note the [] here allow you to use a variable as identifier

let name = "test1"
let a = {
  "test2": function () { return "you called test2" },
  "test3"() { return "you called test3" },
  
  
  [name]() { return "you called test1" },
  [name + "1"]() { return "you called " + name + "1" }
}

// written differently works the same
console.log( a.test2() ) // "you called test2" <-- the old way declared one
console.log( a.test3() ) // "you called test3" <-- new way declared one

// same call
console.log( a[name]() ) // "you called test1" <-- declared using
console.log( a.test1() ) // "you called test1" <-- [name]() {...}

// the [...] notation allow the build of identifier freely 
console.log( a.test11() ) // "you called test11"      <-- declared using
console.log( a[name + "1"]() ) // "you called test11" <-- [name + "1"]() {...}

since Javascript like many other language tend to avoid deprecation for old program to continue working, you get to a point where one thing can be done many way

Upvotes: 5

JoelDoryoku
JoelDoryoku

Reputation: 384

Advantages:

  • Functions are declared normally and therefore have names. (Whereas with the {name: function() { ... }} format, all of your functions are anonymous, even though the properties referencing them have names.) Names help tools help you, from showing call stacks in a debugger, to telling you what function threw an exception. (2015 Update: The latest JavaScript specification, ECMAScript 6th edition, defines a large number of ways the JavaScript engine must infer a function's name. One of those is when the function is assigned to a property as in our {name: function() { ... }} example. So as engines implement ES6, this reason will go away.)

  • Gives you the freedom of having private functions only used by your module (such as my internalSomething above). No other code on the page can call those functions; they're truly private. Only the ones you export at the end, in the return statement, are visible
    outside the scoping function.

  • Makes it easy to return different functions depending on environment, if the implementation just changes completely (such as IE-vs-W3C stuff, or SVG vs. Canvas, etc.).

Upvotes: 1

connexo
connexo

Reputation: 56754

It allows to use variable property names:

let propName = "test"
console.log({ [propName]() { return 1 } }.test());

Upvotes: 1

Related Questions