Ensure that immutability is strictly enforced, or allow for partial immutability without the risk of silently failing

Is there a method to implement partial immutability on an object in a way that triggers an error if any attempt at mutation is made?

For instance, consider let obj = {a: 1, b: 2}. I am interested in making obj.a and obj.b immutable while still allowing additional keys to be added to the object, such as obj.c = 3.

One approach I contemplated was nesting properties within sub-objects and utilizing Object.freeze like this:

let obj = {subObj:{a: 1, b:2}}; 
Object.freeze(obj.subObj);

However, it seems that subsequent changes fail silently. For example, obj.subObj.a = 3 does not alter a, nor does it raise any indication of an issue. Is there a way to ensure an error notification is triggered instead?

Answer №1

A straightforward approach to handle this situation would be to use getters that return fixed values and setters that raise exceptions.

let obj = {
  get a() {
    return 1;
  },
  set a(val) {
    throw new Error('Can\'t set a');
  },
  get b() {
    return 2;
  },
  set b(val) {
    throw new Error('Can\'t set b');
  }
};
obj.c = 3; // works
console.log(obj);
obj.a = 4; // throws an error

Answer №2

Utilize Object.defineProperties() method and set the writable parameter to false for attributes "a" and "b", along with using "use strict" declaration and implementing try..catch..finally statements.

"use strict";

let example = new Object;

Object.defineProperties(example, {
  "a": {value:1, writable: false},
  "b": {value:2, writable: false}
});

try {
  example.c = 3;
  example.a = 3;
} catch (error) {
    console.log(error);
} finally {
    console.log(example);
}

Answer №3

One potential solution is to implement the use of strict mode.

Simply add the following line at the beginning of your file:

'use strict'

This will generate an exception if any modifications are attempted on a frozen object.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to implement MV* in Polymer using models and services as polymer elements?

Imagine I want two views (polymer-elements) to share a model, how can this be achieved? In Angular, the model would reside in a singleton service that is injected into the views, allowing both views to access the same data source. I attempted to replicat ...

Identifying page elements in Protractor when they lack obvious identifiable properties

Scenario Here is the HTML code snippet using an Angular JS template: <div class="data-handler-container"> <div class="row"> <div class="data-handler" ng-if="dataController.showDistance()"> <p>{{ 'Item ...

Swapping one div for another, all the while incorporating a limited number of buttons within the webpage

I'm faced with a dilemma on my HTML page. In the middle of the content, there's a div that contains 4 links with images and text inside. What I'm looking to achieve is for each link to trigger a complete change in the div when clicked, with ...

Specialized function to identify modifications in data attribute value

I have a container with a form inside, featuring a custom data attribute named data-av Here is how I am adding the container dynamically: > $("#desti_div").append("<div class='tmar"+count+"'><div > class='form-group col-md-6 ...

Display all saved bookmarks by utilizing JavaScript

How can I utilize Javascript to display a complete list of my bookmarks? Any advice on achieving this would be greatly appreciated. Thank you in advance. ...

What is the best way to reposition a column as a row when the user interface transitions to a different screen or

Welcome to my UI experience! https://i.stack.imgur.com/gOwAn.png Check out how the UI adapts when I resize the browser: https://i.stack.imgur.com/MyxpR.png I aim for the left component to be visible first, followed by scrolling to see the right compone ...

Can the CSS of an iframe be modified if the iframe is located on a different domain?

Is it feasible to modify the CSS of an iframe if the iframe is not located on the same domain? If so, what are some ways to apply and alter CSS for this situation? Any assistance would be greatly appreciated. <iframe id="frame1" width="100%" height="35 ...

What is the best way to format specific text as bold within an input text field?

I am attempting to make certain text bold within an input text field. However, I'm uncertain about how to achieve this because HTML code is not recognized inside a text field. Therefore, using <b> will not be effective. Is there a way to bold sp ...

Obtain the dimensions (width and height) of a collection of images using Angular and TypeScript

Currently, I am facing an issue with my image upload functionality. My goal is to retrieve the width and height of each image before uploading them. However, I've encountered a problem where my function only provides the dimensions for the first image ...

Utilize Webpack to import a file containing exclusively global constants

I have a specific file filled with essential global constants that I am attempting to bring into another JavaScript file. This way, I can utilize these constants within the code of the second file. globalConstant.js global.RoutesOffersPage = { routes: ...

What methods can I use to adjust the selected option according to the value in the database?

To introduce you to my work, I have a table filled with data from a database that functions as a CRUD - Create, Read, Update, Delete table. Within this table, there is a column where EDIT and DELETE buttons are located. Clicking on the EDIT button trigger ...

Modify the ColVis Appearance in Datatable Using JavaScript

Where can I modify the background color for the 'Hide/Show columns' label in the ColVis.js file? ...

Defining global 'require' scripts in Node.js

Seeking a solution to a slightly unusual problem. I hope that using simple examples will clarify my query, as explaining my complex usage can be challenging. I am incorporating my custom modules into the routes.coffee file for an Express server. My goal i ...

I possess a JSON array object and need to identify and extract the array objects that contain a specific child node

const jsonArray = { "squadName": "Super hero squad", "homeTown": "Metro City", "formed": 2016, "secretBase": "Super tower", "active": true, "members": [ { "name": "Molecule Man", "age": 29, "secretIdent ...

Issues arise when attempting to send an AJAX POST request within WordPress

After going through multiple resources, all mentioning the same approach that I am following, I have two essential files for this process: In the receiver.php file: <?php add_action( 'wp_enqueue_scripts', 'my_enqueue' ); ad ...

"Passing data from a child component to a parent component using Vue's emit

offspring template: ` <li v-for="option in listaOptiuni" :key="option.id"> <input @change="updateSelectAllToateOptiunile(); sendListaToateOptiunile()" v-model="listaToateOptiunile" :value="o ...

Is it possible for a button to be assigned to a variable upon creation, but encounter an error when trying to

const button:Element = document.createElement("button");//This works fine const button:HTMLButtonElement = document.createElement("button");//This works too const button2:Element = document.getElementsByTagName("button");//Why does this give an error? con ...

Tips for incorporating line breaks into a contenteditable div using the key combination of ctrl + enter

$("#contenteditable").keydown(function(e) { var last = false; if (e.keyCode == 13) { if (e.ctrlKey) { let brNode = document.createElement('br'); let range = window.getSelection().getRangeAt(0); ...

The system encountered an error while trying to access the property "slug

I am currently working on a project that involves using next.js and wordpress. I have set up my api.js file, but I encountered an issue when trying to access the [slug] property from another component. The error message displayed is "Typerror: Cannot read ...

Encountering problem when trying to upload several images at once using a single input in CodeIgniter with

I'm attempting to use CodeIgniter and AJAX to upload multiple images using a single input field. Here's the code I have so far: HTML: <input type="file" name="files[]" id="file" multiple /> AJAX: $("#addItems").on("submit",function(e) { ...