You cannot meaningfully include critical hits without factoring in hit probabilities
A brief discussion of random variables: a measurable function defined on a probability space that maps from the sample space to the real numbers.
The damage done on a hit is a random variable - let's call it \$D\$. Its made up of other variables, some random and some not:
$$
D=\sum_{n=1}^\text{diceNumber}U(\text{diceSides})+\text{bonuses}
$$
where \$U(n)\$ is the discrete uniform distribution from \$1\$ to \$n\$ a random variable and the other variables are your variables.
This can simulate \$U(n)\$ although note that the rand
function is only pseudorandom but that won't matter for your purposes:
Math.floor(Math.random() * n + 1)
Since a critical hit doubles the number of dice and the bonuses, it is represented by the random variable:
$$
C=\sum_{n=1}^{2\times\text{diceNumber}}U(\text{diceSides})+2\times\text{bonuses}
$$
For averages, you can calculate all possible outcomes with nested for loops and then work out the average. However, there is a mathematical short-cut - the mean of the sum of independent random variables is the equal to the sum of the means. Similarly, the variance of the sum of independent random variables is equal to the sum of the variances.
So:
$$
\begin{align}
\bar D &= \text{diceNumber} \times \left(\bar U(\text{DiceSides})\right) +\text{bonuses}\\
&= \text{diceNumber} \times \left({{\text{DiceSides}+1}\over 2} \right) +\text{bonuses}\\
\bar C &= 2 \times \left( \text{diceNumber} \times \left({{\text{DiceSides}+1}\over 2} \right) +\text{bonuses}\right)\\
\end{align}
$$
So, now we circle back to why you need a random variable to represent your hit chance. For any given combination of armour class and to hit bonuses there is a target number \$t\$ that you need to roll on a d20 equal to above which is a hit and below which is a miss and if you roll a 20 you get a critical. I am assuming that a 20 is always a hit and always a critical hit: if you can miss on a 20, you need to adjust what follows.
So the damage from an attack, including the chance to hit, can be represented by another random variable:
$$
H = \begin{cases}
0, &U(20)\lt t\\
D, &20\gt U(20)\ge t\\
C, &U(20)=20\\
\end{cases}
$$
If you are only interested in averages, you get:
$$
\bar H = \sum\begin{cases}
0\times Pr(U(20)\lt t)\\
\bar D \times Pr(20\gt U(20)\ge t)\\
\bar C \times Pr(U(20)=20)\\
\end{cases}
$$
Where \$Pr(E)\$Pr is the probability that event \$E\$ happens.
For \$20\ge t \ge 1\$, \$Pr(20\gt U(20)\ge t)=0.05\times (20-t)\$, for \$t\gt 20\$, \$Pr(20\gt U(20)\ge t)=0\$ and for \$t\lt 1\$, \$Pr(20\gt U(20)\ge t)=0.95\$. \$Pr(U(20)=20)=0.05\$ always.