2

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 
}
Omama Zainab
  • 741
  • 4
  • 14
  • 24
  • where do you make the object? – Nina Scholz Sep 14 '20 at 07:17
  • 1
    maybe use `return`? – bill.gates Sep 14 '20 at 07:18
  • 1
    `const idGenerator = () =>{ Math.floor(Math.random() * 1000000) }` will only produce `undefined` since you have no `return` statement. Either add `return Math.floor(Math.random() * 1000000)` or remove the curly brackets around the body `{` and `}` – VLAZ Sep 14 '20 at 07:19
  • 1
    Does this answer your question? [Why doesn't my arrow function return a value?](https://stackoverflow.com/questions/45754957/why-doesnt-my-arrow-function-return-a-value) – VLAZ Sep 14 '20 at 07:24
  • 1
    Also relevant [When should I use `return` in es6 Arrow Functions?](https://stackoverflow.com/q/28889450) – VLAZ Sep 14 '20 at 07:25

1 Answers1

3

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

bill.gates
  • 14,145
  • 3
  • 19
  • 47
  • 1
    I tried your code but it still was getting error then I put a parenthesis while using idgenerator it was working fine. Thanks :) – Omama Zainab Sep 14 '20 at 07:38