Can a variable be made readonly in Node.js

Can a variable be made readonly in Node.js

Problem

I want to prevent a variable from being changed. Specifically a property of an Object:

var foo = { bar: 'baz' };

// do something to foo to make it readonly

foo.bar = 'boing'; // should throw exception

Can this be done?

Problem courtesy of: EvdB

Solution

You could try

Object.defineProperty(foo, "bar", { writable: false });

and the later assignment either fails silently or, if you are in strict mode, throws an exception (according to David Flanagan’s “JavaScript : The Definitive Guide” ).

Solution courtesy of: lmsteffan

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *