Mark As Completed Discussion

Enums

TypeScript has support for enums whereas JavaScript doesn’t support enums natively. To define an enum in TypeScript, we have the enum keyword. It is similar to an object notation but doesn’t have the equals operator nor key-value pairs, just comma-separated values.

JAVASCRIPT
1enum Colors { 
2    red, 
3    green, 
4    yellow, 
5    blue 
6}
7console.log("My favorite color is: " + Colors.blue);

To do the same thing in JavaScript, we would have to write a bit more code. Even though this is just an object notation with key-value pairs, we freeze the object using the Object.freeze() method. This will make sure that the first-level object parameters stay the same and cannot be mutated.

JAVASCRIPT
1const Colors = {
2    red: "red",
3    green: "green",
4    yellow: "yellow",
5    blue: "blue"
6}
7Object.freeze(Colors);
8console.log("My favorite color is: " + Colors.blue);

Do note that object freezing doesn’t ensure complete immutability for nested objects, but only for the first level. Another drawback of using enums this way is in terms of readability. The key-value pairs both reflect the same information and is not very elegant.