Hi,
I’ve just done task 3 from ’ Functions — reusable blocks of code’ chapter . Could you look at my solution: Functions 3
Hi,
I’ve just done task 3 from ’ Functions — reusable blocks of code’ chapter . Could you look at my solution: Functions 3
Hi @CX-Cris,
I started looking at your code thinking what has this person done to make it so complicated… then I realised I had done it wrong when I did it So a big thank you for making me aware of my own error. I forgot that there was a need for two bounds.
I looked at your code and the aim of task 3 of Functions test your skills. Three points were raised here.
- Refactor the code that generates the random number into a separate function called
random()
, which takes as parameters two generic bounds that the random number should be between, and returns the result.- Update the
chooseName()
function so that it makes use of the random number function, takes the array to choose from as a parameter (making it more flexible), and returns the result.- Print the returned result into the paragraph (
para
)'stextContent
.
In respect of point 1 you have created a random function but not as they say by naming it random. I would have chosen:
function random() {
// code here
}
I would apply the same to the chooseName function.
I am curious, as I am not a expert in maths, if the + 1 is needed:
let first = 0;
let last = names.length-1;
let number = function(first, last){
return Math.floor(Math.random() * (last - first + 1) + first);
};
According to MDN Getting a random integer between two values you dont need the + 1 but then I think you would have to remove the +1 and the -1 from your code. I am still trying to figure out the logic in this.
I also agree with the way you add two parameters to the chooseName function so that it takes random() function as well as the array. Something else that I missed on.
Nice work and thanks for sharing the code.