Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 443
Harikrishnan Avatar asked Oct 25 '18 05:10

Harikrishnan


People also ask

Can we create function inside object?

You can call a function inside an object by declaring the function as a property on the object and invoking it, e.g. obj. sum(2, 2) . An object's property can point to a function, just like it can point to a string, number or other values. Copied!

Which is true about anonymous function?

An anonymous function is a function that was declared without any named identifier to refer to it. As such, an anonymous function is usually not accessible after its initial creation. Normal function definition: function hello() { alert('Hello world'); } hello();

Can an anonymous function be assigned to a variable?

An anonymous function in javascript is not accessible after its initial creation. Therefore, we need to assign it to a variable, so that we can use its value later. They are always invoked (called) using the variable name. Also, we create anonymous functions in JavaScript, where we want to use functions as values.

Can you pass a anonymous function as an argument to another function?

Summary. Anonymous functions are functions without names. Anonymous functions can be used as an argument to other functions or as an immediately invoked function execution.

Can an anonymous function be called immediately in a function?

But it can be defined inside the flow of a function and even invoked immediately. An anonymous function can be assigned to a variable and be called using the variable name. Here is an example showing an anonymous function assigned to a variable. Anonymous functions, when assigned to a variable, can be called using the variable name.

How to use anonymous functions as properties in a class?

// Ah-Ha! When using anonymous functions as properties in Classes, note that there are three name scopes: one for constants, one for properties and one for methods. That means, you can use the same name for a constant, for a property and for a method at a time.

How to pass an anonymous function as a parameter in JavaScript?

As JavaScript supports Higher-Order Functions, we can also pass anonymous functions as parameters into another function. Example 3: In this example, we pass an anonymous function as a callback function to the setTimeout () method. This executes this anonymous function 2000ms later. console.log ("Welcome to GeeksforGeeks!");

What is the origin of anonymous functions?

Anonymous functions originate in the work of Alonzo Church in his invention of the lambda calculus in 1936, before electronic computers, in which all functions are anonymous. In several programming languages, anonymous functions are introduced using the keyword lambda, and anonymous functions are often referred to as lambdas or lambda abstractions.


3 Answers

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.

like image 159
josebreijo Avatar answered Oct 22 '22 06:10

josebreijo


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.

like image 30
Matt Way Avatar answered Oct 22 '22 06:10

Matt Way


You could try structuring it like this:

var obj = {
    ac: 10,
    hello: function(){
        console.log("Goodbye");
    }
}
console.log(obj.ac);
console.log(obj.hello());
like image 28
Jamin Avatar answered Oct 22 '22 08:10

Jamin