Hi guys!
I just created a very simple function to generate the random message, but when I had a look at people’ projects, I realized that mine is a super simple. Did I understand the task wrong?
const myRandom = () => {
const myMessage = [‘You can do this’, ‘You are clever’, ‘You will become a developer’, ‘You will achieve great results’];
const genMyMessage = Math.floor(Math.random() * myMessage.length);
const randMessage =myMessage[genMyMessage]
return randMessage
}
console.log (myRandom())
1 Like
Looks right! What are other people doing that makes you think otherwise?
Looks fine. You could squish those last three lines into one, but the logic would be the same. e.g
// const genMyMessage = Math.floor(Math.random() * myMessage.length);
// const randMessage =myMessage[genMyMessage]
// return randMessage
return myMessage[Math.floor(Math.random() * myMessage.length)];
Note, you have to declare the array before you can grab then length of it.
You could write another generalized function and pass it your array. e.g.
const randPick = arr => arr[Math.floor(Math.random() * arr.length)];
const myRandom = () =>
randPick([‘You can do this’, ‘You are clever’, ‘You will become a developer’, ‘You will achieve great results’]);
Going the other direction, if you don’t fully understand the logic you might find a ton of if..then..else
thingies. There’s never a single why to solve a programming problem.
1 Like
Thank you for your all responses and advices. There is a lot what to think about… Thanks!