Assesment wanted for Functions 1 & 2 skills text

Hi there,

I have attempted the exercises 1 & 2 of the following link with succesfull results.

However, after checking for other topics, I found the results provided, and they are different to the ones I have come up with. I´d like to know if my code is correct, and good practice. If not, I would like to understand why the provided results are better.

Thanks in advance.

Code for Exercise 1;

    let names = ['Chris', 'Li Kang', 'Anne', 'Francesca', 'Mustafa', 'Tina', 'Bert', 'Jada']
    let para = document.createElement('p');
    
    function chooseName () {
        para.innerHTML = names[Math.floor(Math.random() * names.length)];
    }; 

    const section = document.querySelector('section');
    section.appendChild(para);

Code for exercise 2

let names = ['Chris', 'Li Kang', 'Anne', 'Francesca', 'Mustafa', 'Tina', 'Bert', 'Jada']
let para = document.createElement('p');

let canvas = document.querySelector('canvas');
let ctx = canvas.getContext('2d');

let x = 50;
let y = 60;
let width = 100;
let height = 75;
let color = 'blue';

function draw() {
    ctx.clearRect(x,y,width,height);
    ctx.beginPath();
    ctx.fillStyle = color;
    ctx.fillRect(x, y, width, height); 
}; 

draw(); 

const section = document.querySelector('section');

Hi there @krast84, and welcome to the community!

Your code is not the same as our code, and other people’s answers, but that’s OK — there is always more than one acceptable solution to these problems.

I’ve tested your examples, and they work fine — great work!

The only bit of feedback I had is that in the draw() function, it would be a better practice to pass all of the values for x, y, width, etc. into the function as parameters, so the functionality is self-contained, it does not rely on global values set from outside, and it can be used to draw many different rectangles, not just a single rectangle.

So for example

function draw(x, y, width, height, color) { ... }

draw(x, y, width, height, color) { ... }
1 Like

Hi @chrisdavidmills

Thank you for your reply and recommendations.

Cris

i noticed i’ve been having the same issue as OP after reading your answer. thanks a lot for posting and trying to help