Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Using Math.floor(Math.random() ) with an object JavaScript

I trying to write a little practice program to get better at JavaScript. It's a random exercise generator. The idea is it picks an exercise at random and logs it to the console. The exercises are sorted in an object and I'm trying to use a function with Math.random to randomly pick an exercise from that object. But I'm not sure why my code isn't working? The function generates a number then feeds it to the objects index, so don't know why it's not working?

const theBigExercise = { exercise: "Bench Press", exercise: "Shoulder Press", exercise: "Deadlift", exercise: "Squats" };

function mainExercise() { let randomMain = Math.floor(Math.random() * 4);

console.log(theBigExercise.exercise[randomMain]);

return randomMain;

}

1 Answer

Jeff Muday
MOD
Jeff Muday
Treehouse Moderator 28,720 Points

It's great your showing your code and ideas-- good stuff!

I think you meant to have a single key/value pair with an array. That makes this work.

Good luck with your JavaScript journey!

const theBigExercise = {
    exercise: ['Bench Press',  'Shoulder Press',  'Deadlift' , 'Squats']
}

function mainExercise() { 
    let randomMain = Math.floor(Math.random() * theBigExercise.exercise.length);
    console.log(theBigExercise.exercise[randomMain]);
    return randomMain;
}

Hi Jeff,

Thanks for the speedy response. Great that's a nice and straight forward fix thanks!

Chris