Deepika Rao
Deepika Rao

Reputation: 155

in javascript what is the * after variable name

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.

Upvotes: 0

Views: 88

Answers (4)

user9147585
user9147585

Reputation: 11

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.

Upvotes: 1

Amit
Amit

Reputation: 46323

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;

Upvotes: 1

Sajal Preet Singh
Sajal Preet Singh

Reputation: 379

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);

Upvotes: 1

Suren Srapyan
Suren Srapyan

Reputation: 68635

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

Upvotes: 1

Related Questions