Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of dividing by 1 javascript

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

like image 712
scrblnrd3 Avatar asked Feb 15 '13 01:02

scrblnrd3


People also ask

What happens when you divide one by a number?

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.

How does division work in JavaScript?

The division operator ( / ) produces the quotient of its operands where the left operand is the dividend and the right operand is the divisor.

What happens when you divide by 0 in JavaScript?

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.

What does /= mean in JS?

The division assignment operator ( /= ) divides a variable by the value of the right operand and assigns the result to the variable.


1 Answers

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)

like image 151
John Conde Avatar answered Nov 03 '22 00:11

John Conde