Need help with recursion js

Tell us what’s happening:
Describe your issue in detail here.
I do not understand any of the hint, nor why I can push a variable type cons that has already been defined, it does not make sense to me that i can modify a cons.

  **Your code so far**

// Only change code below this line


function countdown(n) {
if (n < 1) {
  return [];
} else {
  const countArray = countdown(n - 1);
  countArray.unshift(n);
  return countArray;
}
}
// Only change code above this line
countdown(10);
console.log(countdown(10));
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36 OPR/76.0.4017.220

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

Hey @UnTalPeluca ,

From what you are asking, it seems like you are confused with how you can push items into an array that was declared into a constant variable. While it is true that a constant variable’s value cannot be changed, but the value of it’s value can. This applies to Arrays and Objects, because and array is a mutable object.
Here’s an example:

const myVar = []; 

myVar = "hello World";
// ^ This is illegal and will cause an error
// because you are trying to reasign a constant variable

myVar.push(0);
// ^ This won't cause an error, because the variable
// is an array, and .push is one of it's methods
// You can mutate the values inside the array

// So you can change the values inside the array,
// but you cannot change the value of the variable

I know this is hard to understand, but I hope this helped even a little. This concept is pretty hard to grasp, but this is true in most programming languages.

2 Likes

Knowing this, everything looks very clear :slight_smile: Thank you very much

Then you should look at the Javascript documentation or other sources on how the keyword actually works and what it does and does not allow :wink:

Catalactics explained it already.

The core thing to keep in mind is, that the name of the variable is merely an entry in a lookup-table where the program stores it’s adress in memory (which is a long string of a hexadecimal number which we as humans can’t really use).
Different declarations of variables influence different aspects of this process, including WHEN the declaration is actually executed.

1 Like

I looked for information on several websites, but they all compare Var, Let and Const in terms of reassignment, scope, etc. But no one mentions this. The documentation will be the first thing you look at next time.

Ok, weird. I’m german and when I did a quick search, I got a german page going into a lot of details, including how const does indeed allow changes on mutable objects…

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