Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why javascript don't have a random function to generate integers? [closed]

I'm using this function to generate random int values :

var r = function(min, max){
  return Math.floor(Math.random() * (max - min + 1)) + min;
};

It works perfectly but makes me wonder ... why there is no randomInt and randomFloat in javascript?

like image 606
rafaelcastrocouto Avatar asked Feb 26 '26 21:02

rafaelcastrocouto


2 Answers

JavaScript has a Number type which is a 64-bit float; there is no Integer type per se. Math.random by itself gives you a random Number, which is already a 64-bit float. I don't see why there couldn't be a Math.randomInt (internally it could either truncate, floor, or ceil the value). There is no good answer as to why the language doesn't have it; you would have to ask Brendan Eich. However, you can emulate what you want using Math.ceil or Math.floor. This will give you back a whole number, which isn't really an Integer typewise, but is still a Number type.

like image 150
Vivin Paliath Avatar answered Mar 01 '26 09:03

Vivin Paliath


Because Javascript doesn't have those types. Pure javascript only has a generic number type.

More info on Javascript types may be found here and here.

You may also want to look into this question: Integers in JavaScript

The marked answer says, and I quote:

There are really only a few data types in Javascript: Objects, numbers, and strings. As you read, JS numbers are all 64-bit floats. There are no ints.

like image 26
Geeky Guy Avatar answered Mar 01 '26 11:03

Geeky Guy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!