DEV Community

Cover image for Freezing Arrays in Javascript
Abd Sani
Abd Sani

Posted on

Freezing Arrays in Javascript

This is a cool tip recently tweeted by Oliver Jumpertz:

💛 JavaScript tips 💛

Arrays are objects. Object.freeze has an effect on them.

This means that you can also make your arrays immutable. ↓ pic.twitter.com/9stpcnRX8k

— Oliver Jumpertz (@oliverjumpertz ) August 18, 2021

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)
Enter fullscreen mode Exit fullscreen mode

And this is the outcome:

[ 'chocolate', 'muffin', 'ice-cream' ]
3
[ 'chocolate', 'muffin', 'ice-cream', 'brownie' ]
4
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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/

Top comments (0)