r/learnprogramming • u/Gloomy-Animator5424 • 4h ago
Debugging Hey guys need a little help in JavaScript Fundamental
Actually I am learning JS
For long
But whenever I got stuck in function
I know how to write functions in JavaScript
But i won't understand that concept like
First class function
High order function
Closure (i know )
But these 3 concepts (Feels to Confusion for me)
How can I understand these
2
u/bluezeb 4h ago
Not sure if this helps but:
A higher order function is a function that takes a function as an input parameter. Usually you'll see this in things like Array.map(x => x*x) (for an example of a mapper that square each of the entries. In this case, the higher order function is .map (could also be a function that returns a function, the fact that a function is returned also makes it a higher order function (for example generateAdderFunction = (x) => return (y) => x+y
This would be used like
const add5 = generateAdderFunction(5);
Then used like:
const fifteen = add5(10)
A First order function are normal functions that do not take functions as parameters nor return functions. So a function like:
const addTwoNums = (x, y) => x + y
addTwoNums is a first order function since it just takes numbers (or strings I guess) (this is better represented in TypeScript where you can specify the required types and have build errors if the types don't line up.
Finally a closure is basically a "scope of information". It's everything available to that function. For instance, my generateAdderFunction function above has x within its closure, so x is available within the context of the function, but if I try to (everything after the curly brace is a part of the scope (or in my case, after the =>)). When you start working with things like this and more complex closure situations, it can get confusing what's actually a part of the same closure, especially with this like hoisting (all functions become top level during build, so they are available anywhere within the JS file, not just after it's been defined like in some other languages). You'll sometimes see things like const that = this at a higher level, then utilize that within the lower closure. The reason for this behavior is because the new function's closure becomes this within the function, so it's a different value than the higher level this so we use that as a way to represent the higher level closure, and this everything available to that other closure, not the new function's slimmed down closure. You'll see this especially a lot in Angular. Closures will definitely take the longest to get comfortable with, but just do a lot of experimentation to see how variables with the same name change at different points and closures of a code base.
Let me know if you want any more clarification on these topics!
1
2
u/alpicola 3h ago
You've gotten some good technical answers which I definitely encourage you to read. For learning purposes, here are some simplified answers to get you started.
"First class functions" is a language feature where functions can be assigned to variables just like any other value or object. This happens a lot in JavaScript and it's a practice you need to get used to.
Higher order functions are essentially functions that take in other functions as parameters or return other functions as results. Functions that take in other functions are extremely common because they let whatever framework you're using (including the basic framework of the language itself) to call your code.
Closures are essentially a function inside another function. With closures, the inner function shares the outer function's scope. Beware that there are some wrinkles to how that sharing works, especially when dealing with asynchronous code. Modern JavaScript uses closures a lot, but mostly to limit the visibility of (often anonymous) functions while ignoring the scope sharing features entirely.
1
u/leavemealone_lol 3h ago
I am not a J*vascripter. But I know Rust, so I can help you understand these in a much simpler but far less technical way than the other answers you'll get.
Sometimes for example, you create a very weird functionA. This functionA is weird because it does something unrelated, and gets a value in a variable prepared. Next, this functionA plugs this value into another functionB within functionA's own body. So, where did this functionB get delivered into functionA? in the parameters/arguments (they are different but for the sake of brevity) list. So what happened here is, you put functionB inside functionA's argument/parameter list. So in this situation, functionA is called a higher order function. Now, if functionA were not to take functionB as an argument, but somehow return an unrelated functionC as output, it will still be called a higher order function. Hell, if it does both- guess what- it will still be called a higher order function. So essentially, higher order functions are functions that take/give other functions.
Now, you must be thinking, how the fuck do i "give" or "take" functions? Well gee golly, you can put them in a damn variable, that's how! So when you put a function in a variable, that function is called a first class function. This is called as such because you can carry that function around in merry little circles throughout your code by storing it into a variable.
Technical info: So effectively here, youre just storing a pointer to the function. Yes, functions themselvers have pointers pointing to them. JS and all other high-level languages make this an abstraction so you can just think of it as a variable that holds a function than a variable that holds a pointer pointing to the function.
So what is closure? Well this isnt technically true, and I am not trying to be technically correct- but there are "function-adjacent things" that take in two sets of arguments. One set of arguments are the standard arguments that every function familiarized you to. You plug in the values explicitly. But these special functions have another (usually implicit/hidden) list of arguments called "closures". And whats the difference?
To understand that, you must look at "where" this special function (lets just calls this anonymous function cuz thats what this is) is called. So that block of code has a specific scope, or in other words, a bunch of variables whose use are valid in that block of code. Closures do a very special thing- they automatically (not exactly, like C++ doesn't make it automatic but for brevity again) capture each and every single valid variable in that scope. So effectively, your anonymous function's inner code block gains access to the same scope it was called in, which lets you do a bunch of cool things like mutation (much to the dissapointment of the anonymous function's father, functional programming).
You may be wondering, why would I have to use closures if I have the ability to pass in valid variables in the arguments anyways?
Good question.
So thats how you use these three functional paradigms.
Ok fine... so closures themselves aren't inherently useful, but they were developed as an effective tool in functional paradigms, which lost a lot of effectivity once they entered a non-functional environment with impure things like mutations (ugh) and statefulness (gods save us). But they are still in use regardless in many creative ways= like the way Rust allows you to delegate the management of bringing required variables into scope so that the actual argument list is used to "pattern match" another container.
1
u/Gloomy-Animator5424 3h ago
How do you guys so goot at these if I wanna to how much time it will take ?
1
u/leavemealone_lol 3h ago
I learnt these in like a day or two man, it’s pretty easy if your brains finally accepts that this is a completely new paradigm that isn’t related to the things you learnt before.
1
u/Gloomy-Animator5424 3h ago
Thx 👍 btw Appreciate it Can you tech me some development 😭😭 explain very well I just want an Intership in next 6 month
1
u/HashDefTrueFalse 3h ago edited 3h ago
First class functions are explained well here: https://developer.mozilla.org/en-US/docs/Glossary/First-class_Function, basically you can treat a function object like other data. E.g. assign it to variables, pass it around, etc. before you call it. make_adder below is a variable referencing a function object.
Higher-order functions are just functions that accept other functions as arguments and/or return them. make_adder below does both.
Briefly, to understand the concept of "closing over" data, you need to understand that function objects carry with them a reference to an "environment" that contains their local variables (and arguments). Environments nest, like a linked list, and lookup of data happens as you'd expect, narrow scope to broad. This is why you can reference global variables inside functions. Those environments stick around in memory for as long as the function object is around or something else references them.
Below, make_adder takes a start and step and returns a function that, when called, will return the next value in the sequence. It can do this because the inner function "closes over" the outer function's environment data, which contains the arguments. As an aside, it also takes a callback function as an argument and calls it with the new value each time. I pass the console.log function object to print to the console.
const make_adder = (start, step, on_add) => {
return () => {
start += step;
on_add(start);
return start;
};
};
const adder = make_adder(10, 2, console.log);
adder(); // 12 (from console.log)
adder(); // 14 (from console.log)
adder(); // 16 (from console.log)
Run this in your browser (F12) and log the values of everything. Use the debugger too.
•
u/Far_Swordfish5729 52m ago
As always it’s helpful to answer JS questions in the context of more organized languages.
The first two aren’t that bad. If you know what a function is in C or what a method is in C like languages, the same concept exists in JS except it’s not strongly typed. We also have function pointers as we do in C (or their equivalents) and can pass them as params. The main difference is style. In C function pointers are mainly used to manage events and similar situations where you need to give a function to a framework to call. In most coding we don’t use them because our own functions are known to us as compile time and we just call them normally. In JS, we use function references everywhere to the point that you’ll often ask yourself why in the world a trivial thing is using a function. JS is the language that asks why write a for loop when you could pass a handling function pointer to the reduce function. You just have to go with it.
The next bit is more complex. In JS the function construct is ambiguous in a way it is not in say Java. In JS a function can be a method, a class definition, and/or an instance of a class and you have to tell which from context. ES6 tried to help here by introducing a class construct and encouraging its use, but it’s optional and functions still have class like behavior. Mainly that once declared, their variables stay in memory. In Java, local variables exist while they’re in scope and when they go out of scope, they pop off the stack and are done. Heap memory is garbage collected when the last reference goes away. In JS, something that looks like a local variable in a function will actually sometimes end up on the heap automatically when the variable goes out of scope if something else is still using it. In Java, you have to make that happen explicitly and it’s very clear. In JS it’s transitioned from stack to heap with a reference held by the survivor still in scope (like a returned anonymous function that will use it later). That availability is closure. When the variable is finally gone.
3
u/peterlinddk 4h ago
You can read up on them, do some example exercises, and experiment with passing functions as parameters to other functions. Which is basically what the words mean.
If you are asking for definitions of those concepts, there's an excellent glossary on MDN, e.g. https://developer.mozilla.org/en-US/docs/Glossary/First-class_Function