I have this function. It works fine. Is there a way to shorten the logic though?
function doNotDuplicateRandomIndex() {
if (randomIndex === 0 || randomIndex === 1 || randomIndex === 2 || randomIndex ===3) {
createRandomIndex();
}
}
I haven’t tried anything else, simply because I don’t know where to start.
3
Answers
Use
.includes()
:Use the Less than (
<
) operator. You’re welcome.In fact, this can be even shorter by removing the brackets from the
if...else
statement.See: Are braces necessary in one-line statements in JavaScript?
Insane, we can make the whole function even shorter by converting it to an arrow function expression.
The
if...else
statement is replaced with a Logical AND (&&
) operator.Nice answer by XMehdi01, the same concept can be converted to an arrow function expression too.
I like the other answer, but in your case I think you could use an object or map to check whether an
id
is used:you could also use Map.prototype.has