So if I look at a bit of javascript like above,
it may run like this:
Function countup(2) called with parameter value 2.
This call creates an object in memory called countUp.
In memory, the object has in it a memory block array named countArray, and a variable block allotted named n where n = 2.
The memory blocks were created by const countArray = countup(n - 1) when n = 2.
if(2 < 1) evaluates false n = 2 & countArray undefined memory block 0.
if(1 < 1) evaluates false n = 1 & countArray undefined memory block 1.
if(0 < 1) evaluates true n = 0 & countArray = , empty array created. The empty array is assigned and filled from stack, first with undefined memory block 1 filled next with value n = 1 replacing undefined memory block 1 then with undefined memory block 0 where n = 2 or countArray [1,2]. Is this what’s happening that output is 1,2?
Thanks for the clarification. So if I’m understanding, functions are not objects with methods and are stored in memory by value or something like that.
Thanks for the help. Based on what you’ve explained, this is now how I understand this recursive function:
A function call, countup(2) is made to the function countup() The function call is processed by the function for the purpose of resolving to a return value. The function’s definition/code describes how a return value can be reached. This process occurs
within a global frame named countup.
Process Steps:
if(2 < 1) evaluates false n=2
countArray evaluates undefined
if(1 < 1) evaluates false n=1
countArray evaluates undefined
if(0 < 1) evaluates true n=0
return (empty array)
countArray.push(1) n=1
return countArray 1
countArray.push(2) n=2
return countArray 1,2
If at that point, countArray receives the return value, it seems to me the output will be 2,1 not 1,2. By global frame, ‘countup’ as a named block of code.
Then from Mozilla, I read this , ‘In JavaScript, functions are first-class objects , because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects. For more examples and explanations, see the JavaScript guide about functions.’