From 9241e3919ef1e4f68b71a1491d368ae6361084aa Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sat, 11 Nov 2017 11:41:40 -0600 Subject: [PATCH] Add Freeze An Object, Sorta as a javascript til --- README.md | 3 +- javascript/freeze-an-object-sorta.md | 44 ++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 javascript/freeze-an-object-sorta.md diff --git a/README.md b/README.md index d02188c..14daafb 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_586 TILs and counting..._ +_587 TILs and counting..._ --- @@ -217,6 +217,7 @@ _586 TILs and counting..._ - [Default And Named Exports From The Same Module](javascript/default-and-named-exports-from-the-same-module.md) - [Enable ES7 Transforms With react-rails](javascript/enable-es7-transforms-with-react-rails.md) - [Expand Emojis With The Spread Operator](javascript/expand-emojis-with-the-spread-operator.md) +- [Freeze An Object, Sorta](javascript/freeze-an-object-sorta.md) - [Globally Install A Package With Yarn](javascript/globally-install-a-package-with-yarn.md) - [Immutable Remove With The Spread Operator](javascript/immutable-remove-with-the-spread-operator.md) - [Initialize A New JavaScript Project With Yarn](javascript/initialize-a-new-javascript-project-with-yarn.md) diff --git a/javascript/freeze-an-object-sorta.md b/javascript/freeze-an-object-sorta.md new file mode 100644 index 0000000..f94ae69 --- /dev/null +++ b/javascript/freeze-an-object-sorta.md @@ -0,0 +1,44 @@ +# Freeze An Object, Sorta + +You can freeze a JavaScript object using `Object.freeze` which will help +enforce some immutability practices. Don't be fooled though, you can still +modify arrays and objects in the frozen object. + +Here is what the docs have to say: + +> The Object.freeze() method freezes an object: that is, prevents new +> properties from being added to it; prevents existing properties from being +> removed; and prevents existing properties, or their enumerability, +> configurability, or writability, from being changed, it also prevents the +> prototype from being changed. + +And here is `Object.freeze` in action: + +```javascript +> const things = {one: "two", hello: "world", cats: ["Von Neumann", "Sosa"]} +undefined +> Object.freeze(things) +{one: "two", hello: "world", cats: Array(2)} + +> things.one = "three" +"three" +> things.dogs = [] +[] +> delete things.hello +false + +> things +{one: "two", hello: "world", cats: Array(2)} + +> things.cats.push("Sneaky") +3 + +> things +{one: "two", hello: "world", cats: Array(3)} +``` + +See the [MDN +Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) +for more details. + +h/t Jake Worth