wobsoriano
wobsoriano

Reputation: 13452

Which of const and let is better to use when declaring array of objects in JavaScript?

Let's say I have an array of users.

const users = [
    { id: 1, name: 'Cena John' },
    { id: 2, name: 'Marcus Ignacious' }
];

Yes, the users variable is not re-assignable. But what if I add some data to it?

users.push({id: 3, name: 'Kanye South'});

I know that the value of users didn't change, only the values inside it.

What I'm wondering is whether there's any convention for preferring let over const when it comes to arrays.

One of my colleagues said that I should use let since the value is updated.

Which one is preferable to use?

Upvotes: 5

Views: 3140

Answers (2)

Tu Nguyen
Tu Nguyen

Reputation: 10179

One of my colleagues said that I should use let since the value is updated.

Which one is preferable to use? Any help would be much appreciated.

A good practice is using const first for every variable declaration. Whenever you feel that you want to reassign that variable to another value, then it's time for changing to let.

In your case, using const is totally fine.

Upvotes: 4

qiAlex
qiAlex

Reputation: 4346

you should use let if

let a = 5
a = 10

or

let a = [12,3]
a = ['s',23]

But you should better use const if

const a = [12,3]
a.push('s')

in this case a doesn't changing - it was a link to the array and it is still a link to the initial array

Upvotes: 5

Related Questions