Math.random() generating same number when put in a function

Viewed 542

Hi I'm working on a react project in which I have to generate random ids so I made this function

const idGenerator = () =>{
    Math.floor(Math.random() * 1000000)
}

when I'm using it directly like this it works fine generates different ids

{ 
   id:Math.floor(Math.random() * 1000000) 
}

but when I make function and use it like this it generates the same id why is that?

const idGenerator = () =>{
    Math.floor(Math.random() * 1000000)
}
// using it to make an object
{
   id: idGenerator 
}
1 Answers

Did you tried it also with an return statement?

const idGenerator = () =>{
    return Math.floor(Math.random() * 1000000)
}

Or shorter

const idGenerator = () => Math.floor(Math.random() * 1000000);

const idGenerator = () => Math.floor(Math.random() * 1000000);

let obj1 = {
   id1: idGenerator(),
   id2: idGenerator()
}

console.log(obj1);

Also you need to execute the function with parenthesis () otherwise your propertie will hold the reference to the function

Related