Wyy the use of Const in the recursive example

Why in the example does it use Const when declaring the array in the recursive example. Declaring it with just var seems to work fine? See below, this passed all the tests.

Your code so far


// Only change code below this line
function countdown(n){
if(n < 1) {
  return [];
} else {
  var countArray = countdown(n-1);
  countArray.unshift(n);
  return countArray;
}
}
// Only change code above this line

var cd = countdown(10);
console.log(cd);

Your browser information:

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

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

As a general rule of thumb

  • Use const if you can

  • Use let if you must

  • Never use var

var is a legacy feature. const and let are the recommended way to declare variables.

Thanks, didn’t make sense as it is an object reference being passed around.

Can you elaborate a little more on what you mean by this?

Yeah, I’m not sure what you mean either.

It is true that in JavaScript all non-primitive variables are references.

It is also true that the countdown() function returns an array, which is a non-primitive type.

const means you will not change the contents of the variable. When you use const with non-primitive variables, it means you will not change which object (really, everything non-primitive is an object in JavaScript) you are referencing.

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