I have a bit of code in Javascript, which returns true when it obviously shouldn't. For context: I have a mindmap and in order to find the most extreme coordinates of the map, I cycle through all nodes and check if this node has a higher/lower value than the currently highest/lowest value. When running the code the method returns wrong values and with console.log() I think I found something weird, but don't know how to fix it.
findMaxX(maxX){
console.log("this.x before test:" this.x);
console.log("maxX before test:" maxX);
if (this.x > maxX){
console.log("this.x:" this.x);
console.log("maxX before:" maxX);
maxX = this.x;
console.log("maxX after:" maxX);
}
this.children.forEach(element => {
maxX = element.findMaxX(maxX);
})
return maxX;
}
What I find in the console is this:
maxX before test:360
this.x before test:288
maxX before test:360
this.x before test:64
maxX before test:360
this.x:64
maxX before:360
maxX after:64
this.x before test:65
maxX before test:64
It seems to be working just fine, but at some point the condition seems to return true for an obviously false statement. Is there some noob mistake I'm doing? Where can I search for errors? My code looks fine to me and I can't see a connection to the observed error. I'm happy for all hints! Thank you
CodePudding user response:
It seems to me that this.x and maxX could be strings. And that's why you obtain these results. Here you can see these examples (run this code snippet):
let xNumber = 64, yNumber = 360;
let xString = "64", yString = "360";
console.log(xNumber > yNumber);
console.log(xString > yString);
And read some information about the comparison of different types in JavaScript here
Also, as a suggestion to obtain what you need (if you want to compare these variables as numbers), I would advise converting them to Number, for example in this way:
if (parseFloat(this.x) > parseFloat(maxX)) {
// here your code
}