Evaluation In Need For Test Your Skills: Functions

Hello sir. here are my attempts

1 A Pen by Cleo (codepen.io)
2 A Pen by Cleo (codepen.io)
3 A Pen by Cleo (codepen.io)
4 A Pen by Cleo (codepen.io)

Eagerly waiting for your assessment and remarks.

Nice work, @Cleo_Shepsut!

Here are my comments:

  • Task 1: :x: Missing different parts. You need to multiply random() with the length of the array to get a random index. Then you have to get the string with this random index from the array. And finally, you need to assign the string to para.textContent so it is display in the output pane.
  • Task 2: :warning: Partly correct. Since we are in the lesson about functions you need to wrap your code in function drawSquare(x, y, width, height, color) { /* ... */ } and then call it. Use those parameters inside the function.
  • Task 3: :white_check_mark: Correct. You could also move para.textContent outside and return the name in chooseName(): para.textContent = chooseItem(names);
  • Task 4: :white_check_mark: Correct. Nice use of the filter() method. :+1:

I hope that helps,
Michael

@mikoMK Michael what do you mean! Task 3 is also wrong.
The random function can generate only numbers from 3 to 8,
therefore the function will never print the first three names and will also print nothing when the random function returns number 8.
@Cleo_Shepsut I suggest you to make a random function (min,max) where the min is 0 and max 7.

Hello sirs, I have made some adjustments on task 2 and 3, I don’t know, if they aligned with your suggestions

Task 1: Only one small thing: It should be names.length and not names.length-1. The random() function gives a number between 0 to slightly less than 1. After multiplying with 8 (array length) we get a number between 0 and slightly less than 8. The floor function will round it down to the next integer, which result in an integer between 0 and 7 (the indices of the array)

Task 2: Better but not quite. You should use parameters on the function and use them inside. When the outside variables change, our code should also draw a different rectangle. This would be the solution:

function drawSquare(x, y, width, height, color) {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = color;
  ctx.fillRect(x, y, width, height);
}

drawSquare(x, y, width, height, color);

Task 3: This is correct now. (@Odi000: I don’t know if Cleo also change the random(), but the function (at least now) looks good)

General note: The power of functions is that they encapsulate code. We give them some values, they calculate something and then return some values. After we have written a function, we don’t have to now how the calculation is done, just what we give and what we get. This lets us also reuse the function multiple times (instead of writing the same code over and over again).

Michael

Hello sir, all corrections adjusted as you suggested. thanks

1 Like

Well done, @Cleo_Shepsut

Now they are fine. :+1: