Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is array.push a form of reassignment?

I'm working in a project with several javascript files and part of what I'm doing right now is both migrating existing code to use newer ES6+ features as well as making sure we're abiding by the AirBnB Eslint Rules.

So, given that context, this is the specific situation:

let meta = [a.platform];

And right below that:

meta.push(a.browserName ? a.browserName : 'any');

So now the linter is giving me a warning: 'meta is never reassigned. Use const instead'.


I understand that meta = somethingNew would be reassigning the variable. But in this case, isn't this variable also something different than what it used to be when it was created?

or, to make it even more clear

Can I use a const to define an array that will receive new items? If not, why?

Also, if not: why is the linter throwing a warning?

like image 824
Jonathan Soifer Avatar asked Aug 09 '17 16:08

Jonathan Soifer


Video Answer


2 Answers

The only thing you have to know is that const has nothing to do with immutability. const simply allows you to prevent reassignment, which means that you cannot do that:

   
// OK 
const foo = '';
const bar = [];
const baz = {};

// WTF are we doing!?
foo = 'Foo';
bar = ['Bar'];
baz = {baz: 'Baz'};

However, in JavaScript, object values are mutable ; contrary to primitive values that are immutable. So if you put a string in a const, you will not be able to modify it at all, even with String.prototype methods (which return new strings).

const str = 'Lorem ipsum';

console.log(str.slice(6)); // This is actually a new string...
console.log(str); // The original string has not been modified!

It is quite different with arrays or object literals, though:

const arr = [];
const obj = {};

arr.push('Foo');
arr.push('Bar');

obj.foo = 'Foo';
obj.bar = 'Bar';

console.log(arr); // Modified!
console.log(obj); // Modified!

At this point, it should be clear: the linter shows this warning because, indeed, meta is never reassigned... A mutation is not a reassignment.

like image 108
Badacadabra Avatar answered Oct 23 '22 00:10

Badacadabra


meta.push() doesn't reassign the variable, it just modifies the array that the variable refers to -- it's still the same array, but with different contents. So you can use const for the variable declaration, since you never make it refer to a different array.

The same is true if you assign to array elements. This is OK:

const meta = [a.platform];
meta[1] = somethingNew;

The second assignment doesn't change meta, it changes the array.

like image 25
Barmar Avatar answered Oct 23 '22 00:10

Barmar