← Back tothis vs that

const enum vs enum

Written byPhuoc Nguyen
27 Aug, 2020
An enum can be declared with or without the `const` keyword. Here are the examples of a regular enum:
enum Direction {
and a `const` enum:
const enum Light {


  1. TypeScript compiles regular enum to JavaScript objects. Given the `Direction` enum above, it will be transpiled to the following JavaScript code:
    var Direction;
    (function (Direction) {
    Direction[(Direction['Up'] = 0)] = 'Up';
    Direction[(Direction['Down'] = 1)] = 'Down';
    Direction[(Direction['Left'] = 2)] = 'Left';
    Direction[(Direction['Right'] = 3)] = 'Right';
    })(Direction || (Direction = {}));
    On the other hand, the `Light` enum is not transpiled at all. You will see nothing if the enum is not used.
    In the other cases, all the enum references are replaced by the inline codes. For example, `console.log(Light.Red)` is compiled as `console.log(0 /* Red */)`.
  2. Because there is no JavaScript object that associates with `const` enum is generated at run time, it is not possible to loop over the `const` enum values.
    TypeScript will throw an error when we try to iterate over the `Light` enum:
    // ERROR
    for (let i in Light) {

Good to know

If you do not want TypeScript to erase the generated code for `const` enums, you can use the `preserveConstEnums` compiler flag.

See also

Questions? 🙋

Do you have any questions? Not just about this specific post, but about any topic in front-end development that you'd like to learn more about? If so, feel free to send me a message on Twitter or send me an email. You can find them at the bottom of this page.
I have a long list of upcoming posts, but your questions or ideas for the next one will be my top priority. Let's learn together! Sharing knowledge is the best way to grow 🥷.

Recent posts ⚡

Newsletter 🔔

If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn