Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

90
Views
Random element between -x and x in javascript

Hi I would like to generate a random number between -x and x in JavaScript. This is what I have :

function randomInt(nb){
let absoluteVal = Math.ceil(Math.random()*nb)
let sign = Math.floor(Math.random()*2)
return sign == 1 ? absoluteVal*(-1) : absoluteVal;
}
console.log(randomInt(4))

It works but it is rather inelegant. I was wondering if somebody knew a better solution. Thanks in advance.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

For example with n = 4, it generates this values:

-4 -3 -2 -1  0  1  2  3  4

In total 9 elements. By using positive values, it generates 0 ... 8 with an offset of -4.

function randomInt(n) {
    return Math.floor(Math.random() * (2 * n + 1)) - n;
}

console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Report

0

Using Math.random() (returns a random number between 0 and 1) allows you to do it ( using Math.ceil() is used to rounds a number up to the next largest integer)

function randomInt(nb){
   return Math.ceil(Math.random() * nb) * (Math.round(Math.random()) ? 1 : -1)
}

console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));

More about Math.ceil() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/ceil

More about Math.random() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!