Practice: Immutable vs. Mutable in JavaScript
Primitive
Example
This example will help you understand that primitive values are immutable. Start by opening a Developer Console in your browser. The sequence is ctrl+shift+J on Windows and cmd+option+J on the Mac. Then, you'll use the "console.log" method to write output to the developer console.
JavaScript
// Using a string method doesn't mutate the string var bar = "baz"; console.log(bar); // baz bar.toUpperCase(); console.log(bar); // baz // Using an array method mutates the array var foo = []; console.log(foo); // [] foo.push("plugh"); console.log(foo); // ["plugh"] // Assignment gives the primitive a new (not a mutated) value bar = bar.toUpperCase(); // BAZ
A primitive can be replaced, but it can't be directly altered.