Assessment wanted for - JSON skill test

Hello, could someone please assess this?

Link to task: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Test_your_skills:_JSON

Link to my code: https://jsfiddle.net/Keyboardguy/p0hu7gjw/8/

Thanks, Keyboardguy

Hi @Keyboardguy

Well solved. Congrats! :clap:

Two improvements:

  • Since we need the index in the outer loop it may be easier to use a traditional for loop or a forEach loop where the index is already integrated.
  • You only need to count one gender, because you can calculate from the total.

Keep up the great work,
Michael

1 Like

Hello,

Thank you for the feedback! I used a for ... of loop just because it looked nicer. Also, counting only one gender and calculating from the total is definitely much more efficient than my code counting both.

Thanks, Keyboardguy

1 Like

this is my code, any suggestions for improvement:

const section = document.querySelector(β€˜section’);

let para1 = document.createElement(β€˜p’);
let para2 = document.createElement(β€˜p’);
let motherInfo = 'The mother cats are called ';
let kittenInfo;

async function populate() {
const requestURL = β€˜https://mdn.github.io/learning-area/javascript/oojs/tasks/json/sample.json’;
fetch(requestURL)
.then(response => response.text())
.then(text => displayCatInfo(text))
}

function displayCatInfo(obj) {
const objJson = JSON.parse(obj);
let total = 0;
let male = 0;
let female = 0;

        motherInfo = motherInfo + objJson.map(catName => catName.name).join(",");
        for (cat of objJson) {
            total += cat.kittens.length;
            for (kitten of cat.kittens) {
                if (kitten.gender === "m") {
                    male += 1;
                } else {
                    female += 1;
                }
            }
        }
        kittenInfo = `Total is ${total} no. of male is ${male} no of female ${female}`
        para1.textContent = motherInfo;
        para2.textContent = kittenInfo;
    }

populate();

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

Hi @issadaas and welcome to the community :wave:

Well done! I have only two small improvements:

  • No need for counting both genders. For example you could just count the males an calculate the females with ${total - male}
  • When using for...of loops we should always use const (or let) for the variable: for (const cat of objJson) {

I hope that helps. :slightly_smiling_face:

By the way, if you plan on doing more tasks it would be helpful if you could share your code in an online editor like https://codepen.io/, https://glitch.com or https://jsfiddle.net/ and create a new topic. Thank you :blush:

Cheers,
Michael