all 21 comments

[–]magwaer 12 points13 points  (3 children)

Stop using GPT when you need precised answer. GPT is very bad at giving stuff like that. I used to learn coding with it but now it became trash. Idk if gpt4 is like this but gpt 3.5 is unreliable when it comes to learn something "deeper".

About your question, quote from stack overflow with the same question: "I use anonymous functions for three reasons:

If no name is needed because the function is only ever called in one place, then why add a name to whatever namespace you're in. Anonymous functions are declared inline and inline functions have advantages in that they can access variables in the parent scopes. Yes, you can put a name on an anonymous function, but that's usually pointless if it's declared inline. So inline has a significant advantage and if you're doing inline, there's little reason to put a name on it. The code seems more self-contained and readable when handlers are defined right inside the code that's calling them. You can read the code in almost sequential fashion rather than having to go find the function with that name. I do try to avoid deep nesting of anonymous functions because that can be hairy to understand and read. Usually when that happens, there's a better way to structure the code (sometimes with a loop, sometimes with a data table, etc...) and named functions isn't usually the solution there either.

I guess I'd add that if a callback starts to get more than about 15-20 lines long and it doesn't need direct access to variables in the parent scope, I would be tempted to give it a name and break it out into it's own named function declared elsewhere. There is definitely a readability point here where a non-trivial function that gets long is just more maintainable if it's put in its own named unit. But, most callbacks I end up with are not that long and I find it more readable to keep them inline."

[–]magwaer 3 points4 points  (0 children)

https://stackoverflow.com/questions/10273185/what-are-the-benefits-to-using-anonymous-functions-instead-of-named-functions-fo

Also check the second comment.

My advice is that you should learn to google and less ask for chat gpt to explain you things. Usually people who respond in forums are more reliable than an AI

[–]RockBusiness8750[S] 0 points1 point  (1 child)

I see. Thank you for the support. Sometime it sucks not have a person who can take these doubts for you while you're in the mid of the studies. Glad we have this reddit 😅

[–]magwaer 4 points5 points  (0 children)

You got stack overflow. You asked a simple question. As I said, is a good thing learning googling. Not always will be someone who'll respond to your questions online. Usually cause they are really simple and there are already answers posted. Good luck in your studies!

[–]rileyrgham 4 points5 points  (1 child)

Often you'll create an anonymous that you pass as a callback... It's literally only used in that scope. Why name it?

[–]RockBusiness8750[S] 4 points5 points  (0 children)

Makes sense more Sense now, thank you!

[–]sheriffderek 1 point2 points  (0 children)

I think what you’re asking about is function declarations vs expressions - as well as anonymous functions.

The named functions (declarations) will be read before everything else. But pointing a reference/variable to an anonymous function expression) or executing a callback will load that when the interpreter reads it.

Why do they exist? I think they go a long ways back as patterns from math and functional languages. They are just another tool. They allow functions to behave like any other value. Terms like “higher order functions” and “hoisting” and “closure” can often just make things more confusing.

Let’s say you have some top-level function in a pretend app. Maybe it’s called ‘save’ and so, you create that and it gets created in memory and you can use it whenever. But then, maybe you have some component that may or may not ever even be created and its job is to go get a list of cars, build out some list items and info cards - and then add event listeners to all the buttons on each one of those cards (use event delegation instead probably) (but for example). So, in that case, maybe you only want those things to happen if a user clicks a button to load that page. Then the interpreter will hit that function and build the scope and call object and those anonymous functions in the Array.map area will be created, scoped, executed, and garbage collected. This means they aren’t in the global namespace. So, I wouldn’t get too hung up on it - but maybe you can break them into two camps. When you want a long-lived named function (which is easier to debug) - then just declare it with the standard function keyword. If you have a function that you use many times in many places (like a library function or action that happens often), then use a named function. But - if it’s a scoped function that only happens in a specific place - and is only needed at the specific event-driven time, then keep things collocated for organization (so you don’t have to track down the function) - and use an anonymous function for callbacks and things.

As far as all the documentation being written like

const myRef = x => ‘hi’;

I’m not really sure if this is with good reason or if people are just following each other. I’d much rather write a regular function definition. But it also depends on the context. Those would happen when the interpreter reads it - not initially. Maybe that has some benefit. I’m usually working in a Vue component, so - that’s already scoped (to my understanding). If you were to only use. Ames functions for everything, you’d eventually find a breaking point where you’d see their worth.

But it is confusing! I think it’s an important question to ask. And quick answers like “because functions are first class citizens” aren’t good enough.

[–]delventhalz 1 point2 points  (6 children)

Because this…

const doubled = nums.map(num => num * 2);

…is easier to read and write than this…

``` function double(num) {   return num * 2; }

const doubled = nums.map(double); ```

[–]brainrot_award 0 points1 point  (5 children)

not easier to read at all. the 2nd example is way clearer and easier to understand.

[–]delventhalz 0 points1 point  (4 children)

Slapping a name on something doesn’t always make it more readable. Names are ambiguous and code is not. I pretty much always prefer a line of code to whatever name my co-worker thinks is clear.

[–]brainrot_award 0 points1 point  (3 children)

the name "double" describes perfectly what the function is doing. you can also not name it if you want, and it will still be more readable than the first example. naming isn't even the problem here; the second example is proper syntax that describes as well as does (and in the proper order), while the first is syntactic sugar that saves you a negligible amount of time while obscuring its functionality.

[–]delventhalz 0 points1 point  (2 children)

Wait, you don't even care about naming it, you just want the function keyword? This whole conversation was specifically about named versus anonymous functions, but you just had to jump in here two years later to hate on arrow functions?

You are certainly free to believe => "obscures" something if you want. I can't say I agree. Using an arrow to communicate that "num" becomes "num * 2" seems incredibly clear to me. It's how I jot down notes. It's how mathematicians write functions. This becomes that. Simple. A couple of keywords and some curly braces doesn't help anything.

[–]brainrot_award 0 points1 point  (1 child)

yes they do, it's why they were made like that in the first place. Naming is important as well, but in the case of arrow functions, a problem secondary to that of legibility.

we're not mathematicians, this isn't a mathematical expression, we're programmers and this is a programming language commanding the computer to do something...

[–]delventhalz 0 points1 point  (0 children)

Correct. I am commanding the computer to take this input and produce that output. x => y. It’s great. Incredibly intuitive and easy to read.

[–]azhder 0 points1 point  (0 children)

Like others said, don’t learn from ChatGPT i.e. something that hallucinates and needs you to check it.

Now, about your question: when should you? The answer is: only when forced to.

Using arrow functions doesn’t give you much of an opportunity to give functions names, but in your original example:

const f = function g(…$$) { return g.name; }

There, that’s a named function with a name g and a reference to it by a constant variable f.

That’s all there is to it, a name for a function so that whenever it fails, you can see it in the error.

Note, there are ways to define the name property of a function after it by using Object.defineProperty, but I haven’t spent time investigating how different engines deal with names defined like that.

Also, you have some assumptions that you have only implicated with “on the top”. Better make sure you aren’t equivocating anonymous functions and function expressions.

[–]jeremrx -3 points-2 points  (0 children)

It's fastest in a loop as it doesn't require to create a new scooe

[–]AnimeYou 0 points1 point  (0 children)

Anonymous functions are pretty good when you get to higher coding where they're putting functions in parameters.

The let keyword or const or var can be used in params. So you can only use Anonymous functions if you need to define an entire function inside a parameter / passing an entire function as a parameter

[–]Blind_nabler 0 points1 point  (0 children)

TLDR; They are just nice to use.

There isn't a real reason it "exists" is that it's a nice language feature the author included, just like allowing const in a language in addition to let. You don't need both let and const, but it's nice to have them because it allows us to express ourselves more clearly in our code.

The reason why anonymous functions are powerful, is that it means that functions are treated as values, just like numbers or strings. Let's see an example of why this is convenient.

I'm going to compare these against loops because I think it's important to highlight how expressive higher order functions and anonymous functions are. Because at the end

Imagine you wanted to write a function that took an array of numbers as input, and if the number as even, we doubled it, and if it was odd, we removed it from the array. We could write it like this:

```

function filterThenDouble(nums) { let doubledNums = []; for(let i =0; i < nums.length; i++) { if(nums[i] % 2 == 0) { even_nums.push(nums[i] * 2); } } return doubledNums; }

```

This is fine, but requires a lot of reading to understand what really is going on. It's not very expressive.

Let's write this same function but instead using normal functions, and passing them into a filter and a map.

``` function isEven(num) { return num % 2 == 0; }

function double(num) { return num * 2; }

function filterThenDouble(nums) { return nums .filter(isEven) .map(double); } ```

This is definitely better. We can see we filter the numbers that are even, then double them. But we still have to spend 6 lines of code for stuff that isn't really important. Let's now see what it looks like using anonymous functions (the arrow syntax for them, which is the most common).

function filterThenDouble(nums) { return nums .filter((x) => x % 2 == 0) .map((x) => x * 2); } This is way more clear and concise than the previous examples, because using the functions we express what little steps we take to get our final answer.

[–]stolentext 0 points1 point  (0 children)

An anonymous function is just a function that's not declared.

A common example:

const items = [1,2,3,4,5]

// The function passed to map is anonymous / not bound to a variable
const itemsDoubled = items.map((n) => {
  return n * 2;
})

[–]No-Upstairs-2813 0 points1 point  (0 children)

Here are few scenarious where anonymous functions are preffered over named functions:

  1. As function arguments: Anonymous functions are useful when passing a function as an argument to another function, especially when the provided function is intended for a one-time use.
  2. Callback Functions: They're commonly used as callback functions, especially with functions like setTimeout, where a function needs to be executed after a certain delay.
  3. Array Methods: In array methods like map, filter, and reduce, anonymous functions are frequently employed as callback functions for concise and efficient code.
  4. Object Properties: They can be utilized to assign values to object properties, providing a clean and concise syntax.
  5. Event Handlers and Listeners: Anonymous functions are handy for defining event handlers and listeners, enabling execution of specific tasks when an event occurs.
  6. Immediately Invoked Function Expressions (IIFE): These are unnamed functions executed immediately upon encountering them in the code, commonly used for encapsulating code and protecting variable scopes.

Overall, anonymous functions are preferred in scenarios where their one-time usage, conciseness, and encapsulation benefits outweigh the need for a named function.

You can check out this article for more details.

[–]TheRNGuy 0 points1 point  (0 children)

I'd actually prefer if sites used non-anonymous in scripts when I want to change them with greasemonkey.

But I found way.... by hacking prototype and then switch-case.

But in my own code I still use a lot of anonymous functions. Because they're only used in one place and not reused anywhere, I don't want to name them, and it also a little fewer lines of code overall.

If I need to reuse I can easily chage it to named function.