Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: Math.floor() is not a function

I have a Node.js Discord Bot, written in discord.js, and I want to make a turn based fighting system, so I made a damage calculation function.

var damage = parseFloat( Math.floor( Math.random() * skill.dmg/5 ) + skill.dmg )
//some other factors, none causing the error
damage = Math.floor( damage )

the code is quite simple, but it's erroring with a

TypeError: Math.floor(...) is not a function

I've checked every other post, done what they did, but nothing worked, I've cleared the cache, I've checked for the camelCase, ...

What should I do?

The main function code:

var damage = parseFloat( Math.floor( Math.random() * skill.dmg/5 ) + skill.dmg )
damage += weapons[ user.inv.armor.weapon ].damage
var crit = ( ( Math.floor( Math.random() * 100 ) + skill.crit ) > 100 ? ( Math.random() + 1 ).toFixed( 1 ) : 1 )
damage *= crit
if ( !tags.includes( 'ignorant' ) ) {
    damage -= enemy.stats.res
    damage *= parseFloat( "0." + ( 100 - enemy.res[ tags[1] ] ) )
    damage -= shields[ enemy.inv.armor.shield ].res
}
damage = Math.floor( damage )damage = Math.floor( damage )
( monster ? enemy.hp -= damage : enemy.profile.hp -= damage )
like image 647
Dia. Frost Avatar asked Apr 07 '18 21:04

Dia. Frost


People also ask

What is Math floor in Javascript?

The Math.floor() function always rounds down and returns the largest integer less than or equal to a given number.

How do you round down in Javascript?

The Math. floor() method rounds a number DOWN to the nearest integer.

What does Math round do?

The Math.round() function returns the value of a number rounded to the nearest integer.


1 Answers

Math.floor does indeed exist, it's not a problem with Math. If Math.floor wasn't a function the error would be:

TypeError: Math.floor is not a function

But you're getting

TypeError: Math.floor(...) is not a function

Which means you're doing:

Math.floor(damage)();

So post the code after damage = Math.floor( damage ) which most likely will be (...), so we can pinpoint the exact error.

try {
  Math.floors(5); // Added extra S on purpose
} catch(e){
  console.log(e.message);
}


try {
  Math.floor(5)();
} catch(e){
  console.log(e.message);
}

Update

The error was triggered in the following code:

damage = Math.floor( damage ) 
( monster ? enemy.hp -= damage : enemy.profile.hp -= damage )

What you were doing, is calling the result of Math.floor which is a number.

damage = Math.floor( damage ); // ; this bad boy was all that was missing.
monster ? enemy.hp -= damage : enemy.profile.hp -= damage;

This is why semicolons are important!

Do you recommend using semicolons after every statement in JavaScript?

yes, I absolutely do

like image 141
Marcos Casagrande Avatar answered Oct 12 '22 23:10

Marcos Casagrande