+ 2

How does "freeze" function in JavaScript?

Any doubt about, after some challenge...

24th Jul 2019, 4:31 PM
Paolo De Nictolis
Paolo De Nictolis - avatar
5 RĂ©ponses
+ 1
Paolo De Nictolis hi, Object are used to store everything in Javascript, and Functions that have access to the object can modify the object, whether intentionally or accidentally. To prevent modification of our objects, one of the techniques is to use Object.freeze(). This method prevents the modification of existing property attributes and values, and prevents the addition of new properties. Let’s see another example: var learner = { name: “Paolo”, role: “Developer” }; Object.freeze(learner); (function() { “use strict”; // TypeError: Can’t add property department, object is not extensible learner.dept= “IT”; })(); Object.freeze method takes an object and renders it immutable So above will give error so to shot out that we can use freezing methods like this ways. If you don’t wish to throw errors all over the place, JavaScript provides another method Object.isFrozen() to detect whether the object is frozen. Continue in next answer.........
24th Jul 2019, 4:53 PM
DishaAhuja
DishaAhuja - avatar
+ 2
Paolo De Nictolis by freezing the object cities you have make your object immutable which means the object will remain same so this way when you assign new city with Barcelona that will make no change in city object value and value will be remain as Madrid which is define earlier this way when you are comparing the console you will getting true as output. You can see that behavior by putting some printing statement. var cities = { spain: "Madrid", italy: "Rome", usa: "Boston" }; Object.freeze(cities); cities2 = cities; console.log(cities2); cities2.spain = "Barcelona"; console.log(cities2.spain); console.log(cities == cities2);
24th Jul 2019, 5:41 PM
DishaAhuja
DishaAhuja - avatar
+ 1
var learner = { name: “Paolo”, role: “Developer” }; Object.freeze(learner); if (Object.isFrozen(learner)) { alert(“learner is frozen!”); } This will froze your output at the console screen or browser screen. Have some 🍎 🍎 🍎 🍎 🍎
24th Jul 2019, 4:55 PM
DishaAhuja
DishaAhuja - avatar
+ 1
var cities = { spain: "Madrid", italy: "Rome", usa: "Boston" }; Object.freeze(cities); cities2 = cities; cities2.spain = "Barcelona"; console.log(cities == cities2); Explain me why console logs "true"
24th Jul 2019, 5:33 PM
Paolo De Nictolis
Paolo De Nictolis - avatar
0
All clear now!
24th Jul 2019, 7:14 PM
Paolo De Nictolis
Paolo De Nictolis - avatar