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.
var str = 'HELLO';
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
strs 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).
var arr = [1, 2, 3];
console.log(arr); // [3, 2, 1]
You can see that even though we did not reassign
arr has been changed by the
reverse method. (Note that not all array methods mutate! Many return brand new arrays, such as
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.