When to use let when to use const

when do we use let and when do we use const?
I know that :

  • use let keybord to create block/local scoped variable
  • const is a special kind of let which you can read only but cannot reassign value to it
  • const value is fixed,

but for example, in the snippet below, we do need to pass in different arguments into the function dont we?

const myConcat = (arr1,arr2)=> {
  "use strict";
  return arr1.concat(arr2);
// test your code
console.log(myConcat([1, 2], [3, 4, 5]));

what I mean is that if the const value should be fixed, (unless its an object) then why are we using it in the snippet? why not use let ?

full explanation here: https://dev.to/sarah_chima/var-let-and-const--whats-the-difference-69e

1 Like

Using const for the myConcat function prevents someone from accidentally redefining myConcat somewhere else in large code base.

1 Like

If you expect a variable to be reassigned later, then use let. In any other cases, use const. Also, know that const only prevent reassigning of a variable; const objects and array can still be modified.

1 Like

for example: in for loop

for(var i = 0; i<3; i++){//do something}

because we KNOW for sure that i will be reassigned later to 1,2,3 that’s why we use let.
is this correct?

Yep, i is reassigned on every iteration; so, use let.
For things like a function where reassigning is most likely an error, use const.
I don’t really see the point of using var anymore.

1 Like