This content originally appeared on DEV Community and was authored by Abd Sani
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/
This content originally appeared on DEV Community and was authored by Abd Sani
Abd Sani | Sciencx (2021-08-19T06:05:39+00:00) Freezing Arrays in Javascript. Retrieved from https://www.scien.cx/2021/08/19/freezing-arrays-in-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.