1

We can create "Enums" in Javascript as follows:

var MyEnum = {
    A: 0,
    B: 1,
}

Can I use empty objects instead of numbers as follows?

var MyEnum = {
    A: {},
    B: {},
}

What's the difference and which should be used? There isn't any specific use case.

Code
  • 6,041
  • 4
  • 35
  • 75
  • 2
    it depends ... on the purpose. please add more context to the question. – Nina Scholz Jul 28 '17 at 10:33
  • 1
    Yes; the difference is that the first thing is numbers and the second thing is objects. It’s hard to tell what exactly you’re asking here. Have you tried using objects? Do you have a specific difficulty? – Sebastian Simon Jul 28 '17 at 10:38
  • "We can create Enums in Javascript as follows" — No, you can't. – Quentin Jul 28 '17 at 10:42
  • [May not be Informative] Did you happen to have a look at [this answer](https://stackoverflow.com/a/30058506/5909393). It is interesting. – Sidtharthan Jul 28 '17 at 10:42

1 Answers1

0

I changed my answer after you edited because just noticed what you are trying.

Yes you can use objects as enum value without any problem. When you define {} in an object, it creates and empty object with unique reference.

{} != {} won't be equal because two different objects with same doesn't mean they are same object. Two red balls you have, these balls are the same ball? No.

But instance.type == MyEnum.ObjectEnum1 will always be true. Because both instance and the MyEnum object shares the same reference to the object.

var MyEnum = {
  A: 1,
  B: 2,
  C: 3,
  ObjectEnum1: {},
  ObjectEnum2: {}
}

var obj1 = {
 type: MyEnum.B
}

var obj2 = {
 type: MyEnum.C
}

var obj3 = {
 type: MyEnum.ObjectEnum1
}


console.log(obj1.type == MyEnum.B); //Should be true
console.log(obj2.type == MyEnum.A); //Should be false
console.log(obj2.type == MyEnum.C); //Should be true


console.log(obj3.type == MyEnum.ObjectEnum1); //Should be true
console.log(obj3.type == MyEnum.ObjectEnum2); //Should be false
Ahmet Can Güven
  • 5,392
  • 4
  • 38
  • 59