Anonymous functions inside an object

  • A+

I have a Javascript snippet like this:

var a = {ac: 10, function(){console.log("hi")}} 

The browser is not throwing an error for this. So it may be valid.

But when I use

var a = {ac: 10, function hi(){console.log("hi")}} 

The browser throws error:

Uncaught SyntaxError: Unexpected identifier

Can anybody tell me how can I make use of the first code in any scenario in Javascript

Thanks in Advance


What's happening here is that ES6 allows you to have a shorthand syntax for function definitions. This: const obj = { method() {} } basically translates to this const obj = { method: function() {} }.

So, when you use this snippet var a = {ac: 10, function(){console.log("hi")}} you're telling the browser that function is not a reserved word for you inside that object, rather the name of the property that you want to use, so you end up with an object that has a method called function.

Btw, you should avoid this in the future, do not use reserved keywords for another purpose.

In the second snippet var a = {ac: 10, function hi(){console.log("hi")}} what's happening is that you're trying to have a function declaration (function hi(){console.log("hi")}) inside an object, and that's a syntax error. By giving the function a name, you changed from a shorthand syntax for methods declarations inside the object to a function definition. If you use a proper naming (avoiding reserved words) for this shorthand syntax, or declare the function outside and reference it inside the object, you shouldn't have problems.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: