Forked from battmanz/immutability-vs-reassignment.js
Created
October 17, 2018 21:28
-
-
Save tp-hk/49ce75fe2d351cfb9ec8adc9f052284e to your computer and use it in GitHub Desktop.
Demonstrates the difference between an immutable object and a variable that cannot be reassigned
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
// CASE 1: The object is mutable and the variable can be reassigned. | |
let o1 = { foo: 'bar' }; | |
// Mutate the object | |
o1.foo = 'something different'; | |
// Reassign the variable | |
o1 = { message: "I'm a completely new object" }; | |
// CASE 2: The object is still mutable but the variable cannot be reassigned. | |
const o2 = { foo: 'baz' }; | |
// Can still mutate the object | |
o2.foo = 'Something different, yet again'; | |
// Cannot reassign the variable | |
// o2 = { message: 'I will cause an error if you uncomment me' }; // Error! | |
// CASE 3: The object is immutable but the variable can be reassigned. | |
let o3 = Object.freeze({ foo: "Can't mutate me" }); | |
// Cannot mutate the object | |
// o3.foo = 'Come on, uncomment me. I dare ya!'; // Error! | |
// Can still reassign the variable | |
o3 = { message: "I'm some other object, and I'm even mutable -- so take that!" }; | |
// CASE 4: The object is immutable and the variable cannot be reassigned. This is what we want!!!!!!!! | |
const o4 = Object.freeze({ foo: 'never going to change me' }); | |
// Cannot mutate the object | |
// o4.foo = 'talk to the hand' // Error! | |
// Cannot reassign the variable | |
// o4 = { message: "ain't gonna happen, sorry" }; // Error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment