Search code examples
javascriptif-statementmathmultiplication

How is it possible that same lines of code work differently from time to time?


I've already noticed that simple multiplication in javascript sometimes gives incorrect results. By incorrect I don't mean floating value problem (2.999999 instead of 3) I mean absolutely incorrect result i.e. 2.6581 instead of 44.919283.

I tried to recreate the situation in short lines of code but I didn't manage to do it. I only notice these errors in my whole program.

For example I have these lines:

 console.log('myHighestBuy = ' + myHighestBuy);
 console.log('theirLowestSell = ' + theirLowestSell);

 if ((theirLowestSell * 0.85) < myHighestBuy){

   console.log('If condition is true');
   offerDeal(name, theirLowestSell, MarketPrice, myHighestBuy)

 } else {

   console.log('Not calling offerDeal()');

 }

What I have noticed, that once it has called offerDeal() function despite the fact it shouldn't had to.

Correct case console logs:

myHighestBuy = 16.22
theirLowestSell = 27.78
Not calling offerDeal()

But once I had in my console this:

myHighestBuy = 16.22
theirLowestSell = 27.78
If condition is true

Why is it possible? Is it if condition failure or multiplication error?


Solution

  • You are missing some piece of key knowledge, but it is impossible to determine what it is given the information in the question.

    My spidey senses tell me that you may be accidentally using a global variable that you thought was local inside one of your functions; this is a common hazard in JavaScript. My suggestion, to discover if that is true or not, is to add

    "use strict";
    

    as the very first line of your file.