← 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

If you found this post helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

Questions? 🙋

Do you have any questions about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
Ask me questions

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