Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any point in using an 'enum' type instead of a string in Javascript?

Tags:

javascript

Coming from a background in statically typed languages, the main benefit I get from enums is compile time error catching.

I'm writing a little program in Javascript, and I find myself wanting something like an enum, perhaps like this:

var Fruit = {
   BANANA: "BANANA",
   APPLE: "APPLE",
   PEAR: "PEAR";
};

But I see no advantage to this. I might as well just use strings everywhere this 'enum' is required.

Should I just be using strings in javascript in place of enum types in other languages?

like image 743
jmrah Avatar asked Mar 31 '16 00:03

jmrah


People also ask

When should we use enum in JavaScript?

Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript. Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.

What is the difference between enum and string?

If your set of parameters is limited and known at compile time, use enum . If your set of parameters is open and unkown at compile time, use strings. Save this answer.

Why are enums bad in TypeScript?

The they are useless at runtime argument and agree, if at runtime some code tries to change the values of one of your enums, that would not throw an error and your app could start behaving unexpectedly ( that is why Object.

When should I use TypeScript enums?

In TypeScript, enums, or enumerated types, are data structures of constant length that hold a set of constant values. Each of these constant values is known as a member of the enum. Enums are useful when setting properties or values that can only be a certain number of possible values.


1 Answers

It is good way to extract common things like magic numbers/strings or similar. Imagine that you have BANANA all over the place then for some reason you need to change BANANA to SOMETHING_ELSE, without approach you are using in question you need to make a change in every single place.

var foo = {
  bar: "baz"
}

So using foo.bar instead of hardcoded string "baz" all over the place, can save your time and possible bugs when it comes to changing "baz" to something else.

like image 96
Srle Avatar answered Oct 03 '22 17:10

Srle