What is the utility of the anonymous function in JavaScript

Example →

var theBiggest = function(a,b) {
	var result;
	a>b ? result = ["a", a] : result = ["b", b];
	return result;
}
console.log(theBiggest(7/9,13/25));	

If the first value is bigger, it gives an array of [“a”, 7/9]
If the second value is bigger, it gives an array of [“b”, 13/25]

1 Like

Not This!

I was asking about the utility of anonymous function.

These returns function in the console →

This returns the whole function the console; there must be some utility of this.

It doesn’t have to be an anonymous function. That code works just as well as a normal function declaration too:

function theBiggest(a,b) {
	// ...
}

You can use the function expression to create a named function too, instead of an anonymous one:

var theBiggest = function theBiggest(a,b) {
	// ...
}

And of course, a function expression can create a named function with a different name too:

var theBiggest = function biggityBoggotyBoo(a,b) {
	// ...
}
1 Like

send some visuals(copyright thing so could not post publically as this site may face some issues) in message so that you can understand what actually I am aksing…

Your image shows that line eight issued a separate console command, perhaps something like this on line 8.

console.log(theBiggest);

What I’m saying, is that the console output is different from the code that you are asking about.

1 Like

Anonymous functions are a bad habit, that make it much more difficult, for example, to follow a stack trace.

Named functions, whether they be function declarations or function expressions, are the only good and reliable options to use.

2 Likes

They also tend to make code messy, harder to understand and nonreusable. Note that in the case of setting an event listener with an anonymous function you would not be able to remove it.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.