Search code examples
javascriptmathformulanan

JavaScript equation returning stinky NaN value


var shaftDepth = 1;
var nextShaftDepth = ((maxThreshold - shaftDepth) / 20) + shaftDepth;
var maxThreshold = 10;

The equation for nextShaftDepth spits out an NaN value.

For context, I'm planning to have an "upgrade" in my game which decreases the distance of "shaftDepth" to "maxThreshold" by 5%. To do this, shaftDepth = nextShaftDepth after the formula is done.

"nextShaftDepth" is expected to be equal to 1.45, but instead it just returns an NaN value. Am I doing approaching this wrong or is my syntax incorrect? Thanks.


Solution

  • var is hoisted, it will be undefined as you're trying to access it before the declaration , change your code to

    var shaftDepth = 1;
    var maxThreshold = 10;
    var nextShaftDepth = ((maxThreshold - shaftDepth) / 20) + shaftDepth;