How to Print An Enum's Properties in JavaScript
Sep 22, 2021
JavaScript doesn't support enums natively, but you can use POJOs to simulate vanilla JavaScript enums as shown below.
function createEnum(values) {
const enumObject = {};
for (const val of values) {
enumObject[val] = val;
}
return Object.freeze(enumObject);
}
// { Up: 'Up', Down: 'Down', Left: 'Left', Right: 'Right' }
createEnum(['Up', 'Down', 'Left', 'Right']);
Using toString() on an Enum
Since an enum is just an object, toString()
doesn't print the actual contents of the enum.
createEnum(['Up', 'Down', 'Left', 'Right']).toString(); // '[object Object]'
You should use Object.keys()
instead, which returns an array of strings containing each of the enum property names.
Object.keys(createEnum(['Up', 'Down', 'Left', 'Right'])); // ['Up', 'Down', 'Left', 'Right']
More Fundamentals Tutorials
- Convert a Set to an Array in JavaScript
- What Does Setting the Length of a JavaScript Array Do?
- Get the Last Element in an Array in JavaScript
- Skip an Index in JavaScript Array map()
- Conditionally Add an Object to an Array in JavaScript
- Validate Emails using Regex in JavaScript
- JavaScript Copy to Clipboard