Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the best way to implement enums in JavaScript?

I was thinking about a nice way to implement an enum-like structure in JavaScript. I came up with a few solutions but which one is the best to use?

static getter class:

class Enum {
    static get A() {
        return 0;
    }

    static get B() {
        return 1;
    }

    static get C() {
        return 2;
    }
}

This can be used like var a = Enum.A // a == 0.

Online I found a solution using an object an freezing it:

const enum = {
    A: 0,
    B: 1,
    C: 2
}

Object.freeze(enum);

This can be used like var b = enum.B // b = 1.

I am wondering if one of this methods is better in performance and in memory usage?

like image 335
ParadoxonModding Avatar asked Nov 17 '25 23:11

ParadoxonModding


1 Answers

You can use as below:

const Colors = Object.freeze({
    A: 0,
    B: 1,
    C: 2
});
like image 123
Pranali Gajjar Avatar answered Nov 20 '25 12:11

Pranali Gajjar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!