'When functions are assigned to variables, how are they stored?
Normally, if you create a variable, it's usually trivial how to store it in memory, just get the size of it (or of all of it's components, for example in structs) and allocate that many bytes in memory to store it. However a function is a bit different from other data types, it's not just some primitive with a set size. My question is, how exactly are functions stored in memory?
Some example code in JavaScript:
let factorial = function(x) {
if(x == 0) return 1;
return x*factorial(x-1);
}
Once defined, I can use this function like any other variable, putting it in objects, arrays, passing it into other functions, etc.
So how does it keep track of the function? I understand that this is eventually compiled to machine code (or not in the case of JavaScript but I just used it since it was a convenient example), but how would memory look after such a function is defined? Does it store a pointer to the code and a marker that it's a function, or does it store the literal machine code/bytecode for the function in memory, or something else?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
