Freezing Arrays in Javascript
Abd Sani
Posted on August 19, 2021
This is a cool tip recently tweeted by Oliver Jumpertz:
💛 JavaScript tips 💛
— Oliver Jumpertz (@oliverjumpertz ) August 18, 2021
Arrays are objects. Object.freeze has an effect on them.
This means that you can also make your arrays immutable. ↓ pic.twitter.com/9stpcnRX8k
Having never used this in my code, I decided to give it a try and see what happens if I try to push an already frozen array.
So this is what I wrote in my Javascript file:
var desserts = ['chocolate', 'muffin', 'ice-cream']
console.log(desserts)
console.log(desserts.length)
desserts.push('brownie')
console.log(desserts)
console.log(desserts.length)
Object.freeze(desserts)
desserts.push('popsicle')
console.log(desserts)
console.log(desserts.length)
And this is the outcome:
[ 'chocolate', 'muffin', 'ice-cream' ]
3
[ 'chocolate', 'muffin', 'ice-cream', 'brownie' ]
4
And once you freeze it, you will get a runtime TypeError:
desserts.push('popsicle')
^
TypeError: Cannot add property 4, object is not extensible
at Array.push (<anonymous>)
at Object.<anonymous> (C:\repo\blog\js-freeze-array\freeze.js:10:10)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
That's good to know, no?
Oh and if you haven't, please follow Oliver on twitter. He shares a lot of tips like this.
Cover image by: https://pixabay.com/illustrations/christmas-background-landscape-4701783/
Posted on August 19, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024