Using Object.freeze does not freeze the elements within an array

When I execute the following:

var test = {
    'test': 5
};

Object.freeze(test);

// Throws an error
test.test = 3;

An error is thrown (as expected), but when I try this instead

var nestedTest = [
    {'test': 5},
    {'test': 6},
    {'test': 7},
    {'test': 8}
];

// Freezing all objects in the array
for (var i = 0; nestedTest.length > i; i++) {
    Object.freeze(i);
};

// Overwrites successfully
nestedTest[0].test = 3;

I find that I am able to modify the values of those objects.

Initially, I thought that being in an array wouldn't affect the behavior of the objects.

Could someone please explain what exactly is happening here?

Answer №1

You've mistakenly frozen the index i instead of the object at this index. Your logic should be:

Object.freeze(nestedTest[i]);

Instead of:

Object.freeze(i);

Within the for loop, here's the corrected code:

// Freeze all objects in the array
for (var i = 0; nestedTest.length > i; i++) {
    Object.freeze(nestedTest[i]);
};

NOTE: There's a small typo in the last line, it should be:

nestedTest[0].test = 3;

I hope this explanation helps clarify things.

var nestedTest = [
    {'test': 5},
    {'test': 6},
    {'test': 7},
    {'test': 8}
];

// Freeze all objects in the array
for (var i = 0; nestedTest.length > i; i++) {
    Object.freeze(nestedTest[i]);
};

// Attempting to overwrite
nestedTest[0].test = 3;

// Not overwritten
console.log(nestedTest[0]);

Answer №2

It is recommended to use <code>Object.freeze(nestedTest[i]);
instead of Object.freeze(i);. Also, replace test[0].test = 3; with nestedTest[0].test = 3;

Answer №3

To improve the conciseness of your syntax, I recommend leveraging Javascript's functional features. For example, using .map for Iterateable data structures eliminates the need for cumbersome and error-prone for loops.

A more concise approach would be:

var nestedTest = [
    {'test': 5},
    {'test': 6},
    {'test': 7},
    {'test': 8}
].map(item => Object.freeze(item));

Alternatively, you could use:

var nestedTest = [
    {'test': 5},
    {'test': 6},
    {'test': 7},
    {'test': 8}
].map(freezeArrayItem);

const freezeArrayItem = (item) => Object.freeze(item);

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

Having trouble importing Bootstrap into Next.js? It seems like the issue may be related to the

I am currently facing an issue with importing bootstrap 5.3.2 (not react-bootstrap) into my NextJS 14.1.0 project that utilizes the new App Router. My goal is to strategically utilize individual Bootstrap components (not through data-attrs). I managed to ...

Several radial progress charts in JavaScript

While attempting to recreate and update this chart, I successfully created a separate chart but encountered difficulties with achieving the second progress. The secondary chart <div id="radial-progress-vha"> <div class="circle-vha ...

Opening a browser tab discreetly and extracting valuable data from it

Greetings to the experts in Chrome Extension development, I am exploring ways to access information from a webpage without actually opening it in a separate tab. Is there a method to achieve this? Here's the scenario: While browsing Site A, I come a ...

Gradually appear/disappear div element with a delay added

Storing divs in an array and deleting them after appending is my current method. Now, I'm looking to incorporate a fade-in and fade-out effect on each div with a delay. Check out this code snippet : var arr = $(".notification"); function display ...

Using Sequelize to Include Model Without Specifying Table Name

I am new to Sequelize I am facing an issue with "Nested Eager Loading" I have 2 tables with a one-to-many relationship Comment Table User Table This is the code I am using for the query Comment.findAll({ include: [User] }) The result I got was ...

Implement the Show/Hide TinyMCE Functionality in your <textarea></textarea> Box

Information I recently added TinyMCE to my website after discovering that a website I frequently visit uses it. While their design and functionality are different, I managed to replicate their look on my own site and now want to implement a specific featu ...

Navigating between pages using React and Material UI

My concept involves a <LandingPage> with a <Top> element that can be modified by user interaction. The <Top> component contains a pageState, which can be changed by clicking buttons on the First and Second pages. Is this considered good ...

Clicking will open the link in both a new tab and the current tab

I'm looking to enable ng click functionality to work in both new tabs and the current tab. The URL is dynamically generated based on a certain condition. Here is the HTML: <a ng-href="{{myPathVariable }} " ng-click=" GoToThemes()" class="shift-l ...

What makes it possible for Vue v3 to handle variables that are undefined?

We are in the process of developing a web application that monitors analytical changes and updates them in real time. While this may not be crucial information, we thought it would be worth mentioning. If you visit Vue.js's official website at https: ...

An argument error in IE 8 caused by an invalid procedure call

Is there a way to access the opener's class in a child window created using window.open? This works smoothly in W3C browsers, but fails in IE 8. On the other hand, I tested using an iframe and it seems to work fine across all browsers. The main goal o ...

Using AngularJS to send a model to ui-select

Here is the scenario at hand: A form includes a directive known as <timeZone ng-model="formModel.timeZone" This directive communicates with a web service to fetch timezone information The directive then presents the timezones in a ui-select dropdown ...

Submitting a JSPX form to interact with PHP backend

Can a JSP/JSPX form be used to submit data to a PHP file? The PHP file will handle validation and database updates, then send a response back to the same JSP/JSPX form. The process should be done using AJAX with jQuery. What steps are involved in achievi ...

I am encountering issues where none of the NPM commands are functioning properly even after updating the

For a few months, I have been using npm without any issues. However, once I installed python/django and created a virtual environment, npm stopped working altogether. An error message similar to the following is displayed: sudo npm install -g react-nativ ...

Pause until the array is populated before displaying the components

Currently, I am using firebase storage to fetch a list of directories. Once this fetching process is complete, I want to return a list of Project components that will be rendered with the retrieved directory names. How can I wait for the fetching to finish ...

JavaScript function is not identifiable

I am currently developing a tic-tac-toe game with 9 buttons that will display either an X or O image depending on the boolean value of the variable isX. The main container for these buttons is a div element with the id 'stage' and each button ha ...

Retrieve the dimensions of an image once rendering is complete, using Angular

I'm currently working on obtaining the rendered size of an image within a component. By utilizing the (load) event, I can capture the size of the image as it appears at that particular moment (pic1), as well as its "final" size after the page has fini ...

Assistance in configuring Zurb Foundation 5 for optimal integration with Laravel

As a relatively new user to Laravel with previous experience using older versions of Foundation, I am currently in the process of setting up a new Laravel project. My goal is to integrate the Foundation framework into my project, but I find myself a bit co ...

Establish a buffering system for the <video> element

Currently, I am facing an issue with playing videos from a remote server as they take an extended amount of time to start. It appears that the entire video must be downloaded before playback begins. Is there a way to configure the videos so they can begi ...

Displaying a div in Vue.js when a button is clicked and an array is filled with

Hey there! I'm having an issue with displaying weather information for a specific location. I want to show the weather details in a div only when a button is clicked. Despite successfully fetching data from the API, I'm struggling to hide the wea ...

Issue with Angular: Unable to update model before modal closure on submit

I have a search form that is displayed within a modal window created using Angular UI Bootstrap. The input fields in the form update the ng-model when submitted. <script type="text/ng-template" id="mobileSearchPanel"> <form> ...