'Anonymous functions inside an object
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
Solution 1:[1]
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.
Solution 2:[2]
What you are doing in your first example is called shorthand method names, and is a newer way of initialising functions in js objects. What is actually happening in your example, is it is taking the name of the object key (and the function name) to befunction. But 'function' can be replaced with any key/name. For example:
var a = {
ac: 10,
other() { console.log('inside other') }
}
You can read more about the different ways to initialise an object here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer
The reason why your second example fails, is simply because it is invalid syntax. If you remove the word function from your second example, it will work as I think you were originally expecting it to.
Solution 3:[3]
You could try structuring it like this:
var obj = {
ac: 10,
hello: function(){
console.log("Goodbye");
}
}
console.log(obj.ac);
console.log(obj.hello());
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | josebreijo |
| Solution 2 | |
| Solution 3 | Jamin |
