Files
Amy Lam 914a7c522d Copy edits (#35536)
* Copy edits to Basic JavaScript section

* Copy edits to ES6 section

* Update index.md
2019-03-29 22:06:58 +05:30

2.4 KiB

title
title
Prevent Object Mutation

:triangular_flag_on_post: Remember to use Read-Search-Ask if you get stuck. Try to pair program :busts_in_silhouette: and write your own code :pencil:

Problem Explanation:

You need to freeze the MATH_CONSTANTS object so that no one is able to alter the value of PI, add, or delete properties .

:speech_balloon: Hint: 1

  • Use Object.freeze() to prevent mathematical constants from changing.

try to solve the problem now

Spoiler Alert!

warning sign

Solution Ahead!

:beginner: Basic code solution:

    function freezeObj() {
      "use strict";
      const MATH_CONSTANTS = {
        PI: 3.14
      };

      Object.freeze(MATH_CONSTANTS);
      
      try {
        MATH_CONSTANTS.PI = 99;
      } catch(ex) {
        console.log(ex);
      }
      return MATH_CONSTANTS.PI;
    }
    
    const PI = freezeObj();

Code Explanation:

By using Object.freeze() on MATH_CONSTANTS we can avoid manipulating it.

Resources

:clipboard: NOTES FOR CONTRIBUTIONS:

  • :warning: DO NOT add solutions that are similar to any existing solutions. If you think it is similar but better, then try to merge (or replace) the existing similar solution.
  • Add an explanation of your solution.
  • Categorize the solution in one of the following categories — Basic, Intermediate and Advanced. :traffic_light: