I was working on a program in javascript which included the modulo operator. Since the modulo operator is bugged in js, I created my own function to do so:
function mod(a, b){
return ((a%b)+b)%b;
}
In one of the larger function of my program, I call on my modulo function, using a given parameter as a and a global variable as b. However, this causes the mod function to spit out incorrect results. Here is a simplified version of my program which recreates the bug (note, the 7 I use as parameter is arbitrary, the bug works with any number):
let global = 6;
window.onload = function(){
document.getElementById("global").onchange = function(){
global = this.value;
testing(7);
}
}
function testing(param){
mod(param, global);
}
function mod(a, b){
let result = ((a%b)+b)%b;
console.log("mod of ", a, " and ", b, " is:", result);
return result;
}
<input id="global" type="number" min="1" value="6">
Using both Firefox’ console and JSFiddle, it appears as if the second parameter, b, is a string instead of a number. I have no idea why though.
Why does Javascript incorrectly think I am using a string, and why does this cause such weird results? How can I fix this other than first typecasting the parameters to ints?
>Solution :
The issue you are seeing is likely because the value property of an input element with a type of "number" returns a string, even if the value is a number. In your code, you are using this value as the global variable, which is then passed as the b parameter to the mod function. When the modulo operator % is used with a string value, it is treated as a string rather than a number, which can lead to unexpected results.
To fix this issue, you can convert the value of the input element to a number before assigning it to the global variable. One way to do this is to use the parseInt function, which converts a string to an integer.
Here is an example of how you can update your code to fix this issue, could you try:
let global = 6;
window.onload = function(){
document.getElementById("global").onchange = function(){
global = parseInt(this.value, 10); // convert the value to a number
testing(7);
}
}
function testing(param){
mod(param, global);
}
function mod(a, b){
let result = ((a%b)+b)%b;
console.log("mod of ", a, " and ", b, " is:", result);
return result;
}
<input id="global" type="number" min="1" value="6">
OR:
let global = 6;
window.onload = function(){
document.getElementById("global").onchange = function(){
global = Number(this.value); // convert the value to a number
testing(7);
}
}
function testing(param){
mod(param, global);
}
function mod(a, b){
let result = ((a%b)+b)%b;
console.log("mod of ", a, " and ", b, " is:", result);
return result;
}
<input id="global" type="number" min="1" value="6">