JS: Why use const here?

Tell us what’s happening:

Just asking why I would need to change this from var to const?

  **Your code so far**

const myConcat = (arr1, arr2) => {
return arr1.concat(arr2);
};

console.log(myConcat([1, 2], [3, 4, 5]));
  **Your browser information:**

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

Challenge: Write Arrow Functions with Parameters

Link to the challenge:

It is mainly a coding preference. However, if you are going to use const, you have to know the kind of data that variable will be holding. const will make sure that the variable is unchanged during its entire life once set. However, var can be changed at any point during the variables life.

Hope that answers your question.

1 Like

I would say it’s more than just a preference, it is an accepted best practice now in JS to always use either const or let when declaring variables and only use var when it is absolutely necessary (which is almost never). And that includes using const whenever possible instead of let.

If you want to develop good coding habits then always prefer const except when you know the value of a variable needs to change, then use let.

5 Likes

Yeah, I would call it best practice. var brings with it things like hoisting, function scoping, etc. These can allow sloppy coding (one of JS’s weaknesses, imho).

only use var when it is absolutely necessary (which is almost never) … always prefer const except when you know the value of a variable needs to change, then use let .

That sums it up well.

But just to be clear, the word “change” here is vague. While it holds up well with primitive types, when you get to reference types, you can still change the values to which the variable refers, you just can’t change (reassign) the reference.

const foo = { bar: 41 };
foo.bar = 42;     // legal
foo= { bar: 42 }; // illegal

So, unless you need to reassign the reference, you can always use const with reference types. This is how reference types work - the primitive types will work the way you expect.

This is often a source of confusion with beginners.

3 Likes

Yeah, I see that confusion a fair amount to. I haven’t decided what I think is the best way to describe pass by reference without too much confusion over the notion of pointers.

1 Like

Yeah, I usually just talk about how addresses work and what a reference type is really doing. But FCC tends to shy away from the reading-based learning that something like that needs. FCC seems to shy away from things that can’t be taught in a small code snippet. I mean, the example can be given, but the higher concept would need more of an explanation, I think.

2 Likes