最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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 es to arrays.

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

Which one is preferable to use?

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 es to arrays.

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

Which one is preferable to use?

Share Improve this question edited May 5, 2020 at 22:06 halfer 20.3k19 gold badges109 silver badges202 bronze badges asked Oct 4, 2018 at 10:55 wobsorianowobsoriano 13.5k25 gold badges103 silver badges177 bronze badges 3
  • 2 If you don't need to overwrite users, const is the way to go – Sebastian Speitel Commented Oct 4, 2018 at 10:59
  • i prefer let if is mutable, like a push to one array, and const for inmutable values const pi = 3,14; but i've not found convention laws for this. – Jordi Jordi Commented Oct 4, 2018 at 11:03
  • 2 Neither is "preferable". Just use a mon convention, developed together with your colleagues, on whether you use const to mean that a value is immutable (and not just the variable). – Bergi Commented Oct 4, 2018 at 11:04
Add a ment  | 

2 Answers 2

Reset to default 5

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

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.

发布评论

评论列表(0)

  1. 暂无评论