Assessment wanted for Functions 1, Functions 2, Functions 3 and Functions 4 skill tests
The instructions for task 3 claim that the code for task 3 is an improvement on task 1. However I don’t see how this is possible because (max - min) + min
is just the same as array.length
because min
is equal to zero.
So as far as I can tell, the code for task 3 is merely a more complicated way of doing the same thing we did in task 1. Is this correct?
It’s a conceptual improvement compared to task 1 that we can see when looking beyond the actual exercises. By extracting the calculation of the random number and putting it into it’s own function, we are now able to use it anywhere in our code. Since we’re making the lower and upper bound dynamic, it now works for more use cases.
Sometimes, code becomes easier overall when we make a certain part more complicated.
I discovered in test 2 that if I take the width and height out of the html attributes and put them in the css the position and size of the square changes.
Also if I write the ctx.fillStyle = color;
under the ctx.fillRect(x, y, width, height);
the square turns black.
Why do these things happen? I have updated my code to show what I mean.
That’s an interesting observation!
I’m not very knowledgeable about canvases. So I fiddled around a bit and found the reason.
When you don’t use the width
and height
attributes of the element the canvas defaults to 300 x 150. By using CSS props on the canvas it gets stretched to that size after it was painted on the original, small canvas. Conclusion: Always use the attributes to define the canvas size.
CanvasRenderingContext2D.fillRect() fills the rectangle with the currently defined fillColor
. This way you can paint multiple shapes with different color in a row by changing the fillColor
before each fillRect()
. In your example the fillColor
defaults to black at the moment on the fillRect()
call.
Couldn’t the code for functions test 3 be simplified by re-writing it without the min
and max
parameters like this:
const names = ['Chris', 'Li Kang', 'Anne', 'Francesca', 'Mustafa', 'Tina', 'Bert', 'Jada'];
const para = document.createElement('p');
document.body.appendChild(para);
function random() {
return Math.floor(Math.random() * names.length);
}
function chooseName(array) {
return array[random()];
}
para.textContent = chooseName(names);
Wouldn’t this do the same thing as the code with the parameters?
It would indeed in the special case of the chooseName()
function, but see my second point from above:
Since we’re making the lower and upper bound dynamic, it now works for more use cases.
It’s the bigger picture that matters in this case.
Just wanted to add in an say thank you for this discussion! I’m currently going through this assessment.
Also @church_craig your CodePen links stopped working. I assume you’ve deleted them. Nonetheless, This is a helpful discussion.