First, understand part of why this is not working, you should understand how values are passed in JavaScript and mutable vs. immutable data types.
Primitive data types (strings, booleans, numbers, null, undefined, and symbol) are passed by copy. They are immutable. This means that the only way to change their value is to reassign its value.
For example:
var str = 'HELLO';
str.toLowerCase();
console.log(str) // 'HELLO'
That’s not going to work. We’re calling a string method on str
, but since strings are immutable, calling methods on them does not change the original string. If we wanted to make it so logging str
will give us hello
, we need to reassign str
s value to be the return result of calling the toLowerCase
method on it.
var str = 'HELLO'
str = str.toLowerCase();
console.log(str); // 'hello'
When dealing with objects, they are passed by reference and are mutable. Calling a method on an object can mutate (change) the object (which is often undesirable, actually).
Example:
var arr = [1, 2, 3];
arr.reverse();
console.log(arr); // [3, 2, 1]
You can see that even though we did not reassign arr
s value, arr
has been changed by the reverse
method. (Note that not all array methods mutate! Many return brand new arrays, such as reduce
, filter
, map
, and slice
);
When you’re unsure whether or not a method mutates an object (arrays are objects), look the method up on MDN.
ETA: There’s also this great new site called Does It Mutate? that shows array methods and whether or not they mutate, as well as code examples.