In Javascript, enums are not a built-in feature. When a variable is not initialized, it defaults to undefined.
For example, these two statements are equivalent:
let twitterfollowers;
let twitterfollowers = undefined
So, when you pass in y
and undefined
into your function, it checks if y === twitterfollowers
, which is essentially undefined === undefined
, resulting in true
.
To mimic an enum, you can assign specific values to your variables like this:
const twitterfollowers = 'twitterfollowers';
const dailylikes = 'dailylikes';
const monthlyvisitors = 'monthlyvisitors';
function socialmediametrics(y) {
if (y === twitterfollowers) {
return "This is A";
} else if (y === dailylikes) {
return "This is B";
} else if (y === monthlyvisitors) {
return "This is C";
}
};
console.log(socialmediametrics(twitterfollowers));
console.log(socialmediametrics(dailylikes));
console.log(socialmediametrics(monthlyvisitors));
Instead of using a string, you can also use a number or any object, like a Symbol if your environment supports it.
Each Symbol instance is unique, making comparisons with ===
work seamlessly.
const twitterfollowers = Symbol();
const dailylikes = Symbol();
const monthlyvisitors = Symbol();
function socialmediametrics(y) {
if (y === twitterfollowers) {
return "This is A";
} else if (y === dailylikes) {
return "This is B";
} else if (y === monthlyvisitors) {
return "This is C";
}
};
console.log(socialmediametrics(twitterfollowers));
console.log(socialmediametrics(dailylikes));
console.log(socialmediametrics(monthlyvisitors));