Prevent Object Mutation

This shows how you can lock an object so its content cannot be modified. if you comment out the line Object.freeze(my_object); it will allow it to be modified again.

JS

function run_function() {
  let my_object = {
    i: "am awesome",
  }
  Object.freeze(my_object);
  my_object.i = "am still awesome"; // this should not change the object as its frozen
  write_result(my_object);
  console.log(my_object);
  return my_object;
}

// this is a common function just to write the content into the result div
function write_result(result) {
  var result_html = document.getElementById("result");
  result_html.innerHTML = result;
}

HTML

<div id='result' class='mb-3 alert alert-primary'>..</div>
<button onclick='run_function();' class='btn btn-primary mb-1'>Run Function</button>

Working Result

..

External Link for Prevent Object Mutation

Other Items in javascript
Page Views

This page has been viewed 362 times.

Search Code
Search Code by entering your search text above.
Welcome

This is my test area for webdev. I keep a collection of code snippits here, mostly for my reference. Also if i find a good site, i usually add it here.

❤👩‍💻🕹

Random Quote
When I realized that, no individual step is hard in any process. Building this airport I'm standing in right now started with a guy writing the architectural plans on paper. That's not hard for him to do. Then laying the first beam isn't had. The whole thing is really hard. So, just take each step kind of piece by piece and when I was able to do that and stop trying to chase this prize and started putting in the work, things just started coming together.
Unknown