19
Codewars Mr. Freeze JavaScript
This article explains how to solve the kata Mr. Freeze from Codewars in JavaScript
There is an object/class already created called MrFreeze. Mark this object as frozen so that no other changes can be made to it.
Provided Code
// mark the MrFreeze object instance as frozen
This kata is testing our knowledge about objects and how to freeze them.
First things first: what is an object?
An object is basically a collection of key-value pairs. Objects can have properties and methods.
Properties store data. Methods are functions that can be performed as actions on an object.
Let's see what an object looks like before we talk more about them:
const person = {
firstName: "Michael",
lastName: "Smith",
createFullName() {
console.log(firstName + ' ' + lastName)
}
};
The person
object above has two properties, firstName
and lastName
. It has one method createFullName
.
You can access the value of firstName
through dot notation like this:
console.log(person.firstName);
// Michael
You can call methods from an object in the same way:
person.createFullName();
// Michael Smith
One cool sidenote is that you can add properties to an object easily using dot notation, too. Just make a new property name and assign it a value:
person.hairColor = "brown";
Now our person
object has three properties:
const person = {
firstName: "Michael",
lastName: "Smith",
hairColor: "brown",
createFullName() {
console.log(this.firstName + ' ' + this.lastName)
}
};
Whew! That was quite a setup. Now let's get back to the original point of the kata: freezing an object.
When you freeze an object, you prevent the object from being changed. That means you can't add new properties or change existing properties. If you try to change the object a TypeError
will be thrown:
Object.freeze(person);
person.eyeColor = "blue"; // this line throws a TypeError
Object.freeze(MrFreeze);
19