Reputation: 13275
Using Node.js (ES6) to loop through each object in a collection such as the one below:
var statuses = [{
statusId: 1,
description: 'New'
},
{
statusId: 2,
description: 'Pending'
},
{
statusId: 3,
description: 'Approved'
},
{
statusId: 4,
description: 'Inactive'
}
];
what is the difference between using:
for (const status of statuses) {
console.log(status.description);
}
and
for (let status of statuses) {
console.log(status.description);
}
The output is identical - is there anything going on under the hood that I should be aware of?
Upvotes: 1
Views: 188
Reputation: 7870
With let, the following is possible - status can be reassigned:
var statuses = [
{statusId:1, description: 'New'},
{statusId:2, description: 'Pending'},
{statusId:3, description: 'Approved'},
{statusId:4, description: 'Inactive'}
];
for (let status of statuses) {
status = {statusId:1, description: 'New'};
console.log(status.description);
}
However the same is not possible with const. If you do not want to accidentally reassign, const is preferable.
Upvotes: 3
Reputation: 5473
let
is block scope declaration. definition/reference is limited to the block of its scope.
const
is used when you want to fix the reference of your declaration to a primitive or object or an array. However is object or array is used, values inside it can still change.
If you do not want to accidentally reassign, const is preferable.
Upvotes: 0