When to use let when to use const

When to use let when to use const
0.0 0

#1

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 ?


#2

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


#3

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


#4

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.


#5

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?


#6

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.