In JavaScript, you can define a readonly property. However, if I try to redefine the value of such a property, nothing happens. The value remains the same, but the exception is not thrown.

Code example:

var obj = {}; Object.defineProperty(obj, 'val', { writable: false, value: 'foo' }); obj.val = 'bar'; console.log(obj.val); // Выведет 'foo'; 

Why is this happening, and how to ensure that such errors are not hushed up?

    1 answer 1

    The ability to define read-only properties appeared relatively recently in ES5. Therefore, for backward compatibility with old code, JavaScript specifically silences such errors.

    If you want such errors not to be hushed up, use strict mode :

     (function() { 'use strict'; var obj = {}; Object.defineProperty(obj, 'val', { writable: false, value: 'foo' }); obj.val = 'bar'; // [TypeError]: "val" is read-only console.log(obj.val); })(); 

    In more detail, the behavior of the assignment operator is described in the ECMAScript specification. Among other things, the "Note" block states that an exception should be thrown only in strict mode.

    It is not necessary to make a note that it is not possible to use it. ]]: undefined } In these cases, a Type Error Exception is thrown.