Assessment wanted for JSON skill test (best practice, best syntax)

Hi, I’d like an assessment of my code.
I didn’t find the exercise difficult and I didn’t encounter problems with JSON, my request is more if my code is efficient, straightforward, not redundant, specifically about the loops I used and how I created the variables, thanks.

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

let para1 = document.createElement('p');
let para2 = document.createElement('p');

let motherInfo = 'The mother cats are called ';
let kittenInfo;

fetch('sample.json')
.then(response => response.text())
.then(text => displayCatInfo(text))

function displayCatInfo(catString) {
  let total = 0;
  let male = 0;
  let female = 0;

  // Add your code here
  const arr = JSON.parse(catString);

  for (const [index, cat] of arr.entries()) {
    if (index === arr.length - 1) motherInfo += `and ${cat.name}.`;
    else motherInfo += `, ${cat.name} `;
    total += cat.kittens.length;
    for (const kitten of cat.kittens) {
      kitten.gender === 'm' ? male++ : female++;
    }
  }

  kittenInfo = `Kittens are a total of ${total}, of which ${male} males and ${female} females.`


// Don't edit the code below here!

  para1.textContent = motherInfo;
  para2.textContent = kittenInfo;
}

section.appendChild(para1);
section.appendChild(para2);

This is the link to the exercise.

Thank you a lot, I’m striving to always follow best practices and use the most appropriate syntax.

1 Like

This is really good code. I didnt use a for of loop to carry the instructions out as I didnt know you could get a key value using the for of. Great use of a conditional (ternary) operator as well.

My code looked like this

newText = JSON.parse(catString);
for (let i = 0; i < newText.length; i++) {
 if (i === newText.length - 1) { 
 motherInfo += ' and ' + newText[i]['name'] + '.';
 } else if (i === newText.length - 2)  {
 motherInfo += newText[i]['name'];
 } else {
 motherInfo += newText[i]['name'] + ', ';
 }
for (let j = 0; j < newText[i]['kittens'].length; j++) {
 total += 1;
if (newText[i]['kittens'][j]['gender'] === 'm') {
 male += 1;
}

}
 
} 

kittenInfo = `There are ${total} kittens and ${male} are male and ${total - male} are female`
 

However I did notice that I had to use one further variable to get your code to work

let female = 0;

I will be looking at your code to learn more. Thank you for sharing.