Const vs Var Keyword

Tell us what’s happening:

The explanatory example uses const keyword to declare the array:
const countArray = countup(n - 1);

In my solution, I have used var keyword which produces the same result. Is there any reason why const should be used instead of var.

Your code so far


// Only change code below this line
function countdown(n){
  
if(n<=0)
return [];

else 
{
var arr = countdown(n-1);
 arr.unshift(n);
 return arr;
}
}
// Only change code above this line
console.log(countdown(5)); // [5, 4, 3, 2, 1]

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64; rv:74.0) Gecko/20100101 Firefox/74.0.

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

When you have a variable that shouldn’t be reassigned (any object, for example), it’s best to use const because then you can’t reassign it. If you have a variable that will be reassigned (strings, for example) it is almost always best to use let.

https://evertpot.com/javascript-let-const

2 Likes

Short answer, just use const and let instead of var.

For the code you have. If you use var the variable will be function scoped, if you use const it will be block-scoped, and as it is only used inside the else block it might as well be scoped to it. You also can’t reassign it.

It won’t really change much for the code, but it might help if you were to later do some code refactoring and by accident did something with the variable you didn’t really mean to (like reassign it or change it outside the else block).

A bit more on let, const, and scope.


You Don’t Know JS: Scope & Closures

2 Likes

const and let also have more sane scoping rules. You can’t shadow a var, so you have to be careful about what you name your vars in any inner block, whereas you don’t need to worry about it so much with const/let unless you’re deliberately capturing outer scope. You also can’t use a const/let before it’s assigned, whereas a var will simply be undefined.

1 Like

Don’t worry about it now, this concept of const is explained very well in the next module i.e. ES6.