+ 2
How does "freeze" function in JavaScript?
Any doubt about, after some challenge...
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.........
+ 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);
+ 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 đ đ đ đ đ
+ 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"
0
All clear now!