I was working on a simple programming exercise my teacher gave us, and I noticed several times that in Javascript, I have to divide a number by 1, otherwise it will return a ridiculous value. Any explanations? I have a jsfiddle http://jsfiddle.net/TpNay/1/
var widthrand=Math.floor(Math.random()*widthRange);
width=widthrand + document.getElementById('width').value/1;
If you look at line 22, and take out the divide by 1, and click generate, it will return ridiculous lengths Thanks
Any number divided by 1 equals itself. This rule tells us simply that if we have a number divided by 1, our answer will equal that number regardless of what that number is. We don't even have to pay that much attention to the number we are dividing.
The division operator ( / ) produces the quotient of its operands where the left operand is the dividend and the right operand is the divisor.
The output of the code in JavaScript is as follows: Dividing the number 0 by 0 returns NaN. Dividing the positive number by 0 returns Infinity. Dividing the negative number by 0 returns -Infinity.
The division assignment operator ( /= ) divides a variable by the value of the right operand and assigns the result to the variable.
It makes JavaScript type juggle forcing the value of document.getElementById('width').value
to become numeric.
A better way to do it would be parseInt(document.getElementById('width').value, 10)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With