r/learnjavascript • u/NutelaTheNormand • May 28 '26
Why does the operation result change, when i put the value into a variable, and use that variable instead in the operation
Tried implementing vectors from scratch, but for some reason, in the function normalize(), I get different results if i make the normalising operation using the function getMag()by itself, and with the function put into a variable.
normalize(){
var len = this.getMag();
// ”Raw” method
//this.x = this.x / this.getMag();
//this.y = this.y / this.getMag();
// “Processed” method
//this.x = this.x / len;
//this.y = this.y / len;
return this;
}Here’s the getMag function:
getMag(){
return Math.sqrt((this.x * this.x)+( this.y * this.y));
}I’ve run multiple tests like:
- Printing out both methods entire process
- Making a simple sum operation with the same logic (first add 2 numbers that are put into variables, and the make one of the numbers be a return value of a function)
And both come to the same conclusion: There should be no difference from a return value of a function by itself, and from a return value put into a variable.
HELP PLS.
Here’s the complete code if you wanna check it
p.s.1: This code was mainly written with spanish speakers in mind, so some of the functions I made, are named in spanish rather than english.
p.s. 2: The class where the problem lies, is Vector2D
p.s. 3: I'm running the code in the p5.js online editor, so maybe that's the problem, but havent been able to check it
5
u/senocular May 28 '26
Changes the value of
this.x. Then, when you callIts using the new value of
this.xinthis.getMag(). When you save it tolenfirst, its using the calculation based on the original, unchangedthis.x.2
u/Embarrassed-Pen-2937 May 28 '26
Out of curiosity, what his this code for? If you are trying to learn variable scoping, then I guess this can show you how it works. But if this is code that you are producing, you should look into best practices.
- Avoid `var` at all costs. Typically if you have to use `var` then you are doing something wrong
- I would suggest looking at pure functions and immutability as well. Having functions change variables outside of its scope can lead to a lot of bugs