DEV Community

Cover image for Codewars Mr. Freeze JavaScript
Dylan Attal
Dylan Attal

Posted on • Edited on

Codewars Mr. Freeze JavaScript

This article explains how to solve the kata Mr. Freeze from Codewars in JavaScript

Instructions

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
Enter fullscreen mode Exit fullscreen mode

Discussion

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)
    }
};
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

You can call methods from an object in the same way:

person.createFullName();
// Michael Smith
Enter fullscreen mode Exit fullscreen mode

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";
Enter fullscreen mode Exit fullscreen mode

Now our person object has three properties:

const person = {
    firstName: "Michael",
    lastName: "Smith",
    hairColor: "brown",
    createFullName() {
        console.log(this.firstName + ' ' + this.lastName)
    }
};
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Solution 1

Object.freeze(MrFreeze);
Enter fullscreen mode Exit fullscreen mode

Hope you enjoyed this article! You can follow me on LinkedIn and GitHub!

Top comments (2)

Collapse
 
kieudac201 profile image
KieuDac201 • Edited

person.createFullName() not print 'Michael Smith'

Collapse
 
dylanattal profile image
Dylan Attal

Thank you!! I forgot this. Classic oversight