0

I am new to javascript and I am trying to get random positive and negative numbers between 1000 and -1000

There was a reply for it in How to get Random number + & -

Here the below suggesion was mentioned

var num = Math.floor(Math.random()*99) + 1; // this will get a number between 1 and 99;
num *= Math.floor(Math.random()*2) == 1 ? 1 : -1; // this will add minus sign in 50% of cases

What is num *? I mean what is this concept called for me to study more on.

31piy
  • 23,323
  • 6
  • 47
  • 67
Deepika Rao
  • 145
  • 1
  • 3
  • 11

4 Answers4

1

This will assign to the num variable the result of num * result of the right side of expression

num *= Math.floor(Math.random()*2) == 1 ? 1 : -1

is just a concise form of writing this

num = num * Math.floor(Math.random()*2) == 1 ? 1 : -1

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
1

The assignment operator '=' can also be written as

/=
+=
-=
%=
*=

and they all stand for

x = x / (right hand side);
x = x + (right hand side);
x = x - (right hand side);
x = x % (right hand side);
x = x * (right hand side);
1

The *= operator is a shorthand for "multiply by", and the following statements are identical:

x *= 2;
x = x * 2;

As for your actual requirement, here's a simple solution:

x = Math.floor(Math.random() * 2001) - 1000;
Amit
  • 45,440
  • 9
  • 78
  • 110
1

If there is a binary arithematic operator before the assignment operator like this

a += b
a -= b
a *= b
a /= b

It means

a = a + b
a = a - b
a = a * b
a = a / b

respectively.