How to find length of enum data in javascript/typescript


Enum is inbuilt in data type used to store multiple contents in a single namespace.

Sometimes, As a developer need to find number of elements of enum in javascript/typescript There is no inbuilt in method to find out the size of properties of an enum.

lets declare enum constants in Javascript, The same code works in Typescript

export enum Color {
    RED = "#FF0000",
    GREEN="#008000",
    YELLOW = "#FFFF00",
    BLUE="#0000FF",
    MAROON="#800000"
}
console.log(Color);

Length of enum properties in Javascript/typescript

There are multiple ways to check the size of an enum type.

First, For loop within operator used to iterate the elements of an array and increment the counter, finally, prints counter values

Second, using object methods keys(), values(), entries() methods to get the array list of keys, values, and key-value multiple constants. These methods return the array of enum constants. using the length method on the array, prints the size.

var size=0
for (let element in Color) {
    if (isNaN(Number(element))) {
        size++
    }
}
console.log('size= '+size) // 5

const values=Object.values(Color);
const keys=Object.keys(Color);
const entries=Object.entries(Color);

console.log(values.length) //5
console.log(keys.length)// 5
console.log(entries.length) //5
Similar Posts