r/learnjavascript • • 6d ago

Coursera Meta Front-End Developer Professional Certificate - HELP

Hello!

I am taking the Meta Front-End Developer Professional Certificate course on Coursera. I am totally new at this. In fact, this is a career change for me. I started this course under the impression it was for beginners. But I am stuck in course 2 of 9, the JavaScript portion. The assignment to get past module 2. I have submitted it 3 times and get the same exact grade. I have no idea what it is asking me to do at this point. I have put in a complaint. I have tried posting to their discussion board. They still have not approved my post. I have gone back through the modules and rewatched and reread everything. I have consulted YouTube videos, and apparently I'm still not doing it right? I am using studio VS like they suggested. Below is the code I wrote, the top data is the starter data they gave me and I will attach a screenshot of the assignment. I understand I am still missing info. But in my last submission, I had all 6 functions, but the score was still 40%. My first 2 attempts barely had 2 functions. I don't see how my score will still be 40%.

P.S. This is my first time posting on Reddit. If this is not the right spot or the right way, please let me know. Thank you in advance.

ASSIGNMENT:
Write a small set of JavaScript utility functions that use arrays, objects, and functions, apply common built-in methods, correctly handle undefined vs null vs "", and demonstrate defensive programming with throw and try/catch.

Submit one code block containing the starter data, all functions, Part C answers (as comments), and the required test calls with expected outputs.

1.

Question 1

Starter Data:

const users = [

{ id: 101, name: " Ada ", scores: [10, 20, 30] },

{ id: 102, name: "", scores: [5, 0, 15] },

{ id: 103, name: null, scores: [7, 14] },

{ id: 104, /* name missing on purpose */ scores: [3, 3, 3, 3] },

{ id: 105, name: "Grace", scores: [] }

];

Tasks (implement exactly these 6 items)

1. normalizeName(value) Return "Unknown" if value is null, undefined, or trims to ""; else return value.trim(). Must use trim() and typeof at least once.

2. averageScore(scores)

  • If not an array: throw new Error("scores must be an array")
  • If empty array: return null
  • Else return average rounded to 2 decimalsMust use Array.isArray() and Math.round() (or equivalent math rounding).

3. buildUserSummary(user)

  • If not a non-null object: throw new Error("user must be an object")Return { id, name, scoreCount, avg } using the rules:
  • name: normalizeName(user.name)
  • scoreCount: number of scores; if missing/not array use 0
  • avg: averageScore(scores); if missing/not array treat as empty → nullMust use dot and bracket notation at least once each.

4. summarizeUsers(userArray)

  • If not an array: throw new Error("userArray must be an array")
  • Return userArray.map(buildUserSummary)Must use map().

5. safeSummarizeUsers(userArray)Use try/catch around summarizeUsers. Return:

  • success: { ok: true, data: ... }
  • error: { ok: false, error: "<message>" }

6. getUserDisplayNameById(userArray, id)

  • If userArray not array: throw new Error("userArray must be an array")
  • If id not number: throw new Error("id must be a number")
  • Use find() to locate user by id; if not found: throw new Error("user not found")
  • Return normalizeName(found.name)

Part C:

// Part C answers:

// 1) typeof undefined = ?

// 2) typeof null = ?

// 3) Why treat "" differently than null/undefined in normalizeName (conceptually)?

Required test calls:

console.log(normalizeName(" Ada ")); // expected:

console.log(normalizeName(" ")); // expected:

console.log(normalizeName(null)); // expected:

console.log(averageScore([10, 20, 30])); // expected:

console.log(averageScore([])); // expected:

console.log(buildUserSummary(users[0])); // expected:

console.log(buildUserSummary(users[3])); // expected:

console.log(safeSummarizeUsers(users).ok); // expected:

console.log(getUserDisplayNameById(users, 105)); // expected:

console.log(safeSummarizeUsers("not an array")); // expected:

const users = [


  { id: 101, name: " Ada ", scores: [10, 20, 30] },


  { id: 102, name: "", scores: [5, 0, 15] },


  { id: 103, name: null, scores: [7, 14] },


  { id: 104, /* name missing on purpose */ scores: [3, 3, 3, 3] },


  { id: 105, name: "Grace", scores: [] }


];


function normalizeName(value) {
    if (typeof value !== "string") return "unknown";
    const cleaned = value.trim().replace(" ");
    return cleaned || "unknown";


}


const normalizedUsers = users.map(user => ({
    ...user,
    name: normalizeName(user.name)
}));
console.log(normalizedUsers)


function averageScore(users) {
    const validScores = users
    .flatMap(user => user.scores || [])
    .filter(score => score !== null && score !== undefined && String(score).trim() !== "")
    .map(Number)
    .filter(num => !Number.isNaN(num));


    if (validScores.length === 0) return 0;


    const total = validScores.reduce((sum, score) => sum + score, 0);
    const average = total / validScores.length;


    return Math.ceil(average);
}
console.log(averageScore(users));


function buildUserSummary(user) {
    const validScores = Array.isArray(user.scores)
    ? user.scores.filter(score => score !== "" && score !== null && !isNaN(Number(score))).map(Number)
    : [];


    const scoreCount = validScores.length;


const total = validScores.reduce((sum,score) => sum + score, 0);
const avg = scoreCount > 0 ? Math.round(total / scoreCount) : 0;


return {
    id: user.id,
    name: user.name,
    scoreCount,
    avg
};


}
const userSummaries = users.map(buildUserSummary);


console.log(userSummaries)


function summarizeUsers(userArray) {
    if (!userArray || userArray === 0) {
        return { totalUsers: 0, averageScore: 0 };
    }


    const totalScore = userArray.reduce((sum, user) => sum + (Number(user.score) || 0), 0);
    const averageScore = Math.round(totalScore / userArray.length);
    return {
        totalUsers: userArray.length,
        averageScore: averageScore
    };
}
const summary = summarizeUsers(users);
console.log(summary);


function safeSummarizeUsers(userArray) {
    if (!Array.isArray(userArray)) {
        return [];
    }
    return userArray.map((user)=> {
        try {
            return buildUserSummary(user);
        } catch (error) {
            return {
                name: "unknown",
                averageScore: 0,
                error: error.message
            };
        }
    });


}
const summaries = safeSummarizeUsers(users);
console.log(summaries);


function getUserDisplayNameById(userArray, id) {
    const user = userArray.find(u => u.id === id);
    return user ? user.displayName : "unknown";
}
const name = getUserDisplayNameById(users, 101);
console.log(name);
1 Upvotes

13 comments sorted by

3

u/CAPTAINCAPSLOCK111 6d ago

Having all six functions isn't enough if they accept different inputs or return different things from what the assignment specifies. I can't tell how their grader assigns points, but there are several concrete mismatches in the code you posted.

Start with averageScore. It's supposed to receive an array of numbers, like [10, 20, 30]. Yours expects an array of users and reads user.scores from each entry. Try calling it with the exact test from the assignment, averageScore([10, 20, 30]), rather than averageScore(users). Those are different inputs. Also, an empty array should return null, not 0, and Math.ceil(average) rounds up to a whole number rather than rounding to two decimal places.

In normalizeName, the required fallback is "Unknown" with a capital U. Yours returns "unknown". Remove .replace(" ") too: trim() already removes whitespace from the ends, and your replace call doesn't supply a replacement.

summarizeUsers should return an array containing a summary for each user. Yours returns one object with a total and an average. safeSummarizeUsers then needs to wrap that result in { ok: true, data: ... }, or return { ok: false, error: ... } if an error is thrown. Currently it returns an array instead.

Finally, getUserDisplayNameById reads user.displayName, but your user objects have a name property. The assignment wants you to pass that name through normalizeName.

I'd fix and test one function at a time, starting with normalizeName, then averageScore, before trying another submission. Check the returned value against each requirement, including capitalization, null, and the required errors. That should give you much clearer feedback than the overall percentage.

1

u/katekatie1776 5d ago

Thank you for the info. It is helpful. Any suggestions on how to learn JavaScript better and more efficiently?

1

u/TheGratitudeBot 5d ago

Just wanted to say thank you for being grateful

1

u/CAPTAINCAPSLOCK111 5d ago

To be completely honest, AI is the best private teacher you could ever get for anything. Be it chemistry, mandarin, japanese, gynaecology or Javascript. you can let it write coursebooks just for you, make assignments, grade you - go through your grading, and let you tell you why you just got a C and what you could do better next time. Its the best thing for learning if done right, not just for slop and quick success.

2

u/CAPTAINCAPSLOCK111 5d ago

For that assignment, I’d take one function at a time and write down the expected result for a few inputs before running it. Include an empty input and an invalid one. That makes it much easier to see which requirement you’ve missed than looking only at the overall grade.

2

u/softgray 5d ago

I dunno, AI hallucinates too much for me to trust it to teach anything accurately. And if you don't already know the subject, you won't know when a hallucination has slipped in. You could end up thinking you know a subject well but only realize you don't once you take a test written by, for example, a professor in the subject.

2

u/softgray 6d ago edited 6d ago

You do have some places where you haven't fully implemented what they asked, and places you're logging the wrong output. Try running the code and take a look at what your code is outputting vs. what they've asked for.

Let's take a look at normalizeName(), for example.

They asked you to log

console.log(normalizeName(" Ada "));

but instead, your code creates an array of normalizedUsers and runs

console.log(normalizedUsers);

Basically, the output they wanted to see in the console is:

Ada

But your current output is:

[
  { id: 101, name: 'Ada', scores: [ 10, 20, 30 ] },
  { id: 102, name: 'unknown', scores: [ 5, 0, 15 ] },
  { id: 103, name: 'unknown', scores: [ 7, 14 ] },
  { id: 104, scores: [ 3, 3, 3, 3 ], name: 'unknown' },
  { id: 105, name: 'Grace', scores: [] }
]

You also haven't fully followed the instructions. Let's take a look at them again, with some added linebreaks to take in each instruction.

Return "Unknown" if value is null, undefined, or trims to "".

Else return value.trim().

Must use trim() and typeof at least once.

So firstly, we want to return "Unknown" if value === null, value === undefined, or value.trim() === "".

But it seems like they want you to make use of typeof instead of === here. The important thing is to know what typeof returns for your three possibilities.

typeof null returns "object"

typeof undefined returns "undefined"

typeof "" returns "string"

Getting "string" as the type doesn't tell us if the string is empty, so we'll have to test that part later. For now, the first part of our function could be:

function normalizeName(value) {
    if (typeof value === "object" || typeof value === "undefined") {
        return "Unknown"
    }
    
}

Then, since they haven't instructed otherwise, let's assume any value that isn't null or undefined is a string.

The functiontrim() removes the whitespace around the beginning and end of a string. We want to run trim() on the input and then check whether the result is "" or not. Note that replace() isn't needed here, because trim() is already removing the spaces we want removed.

So we can complete our function like this:

function normalizeName(value) {
    if (typeof value === "object" || typeof value === "undefined") {
        return "Unknown"
    }
        
    const trimmed = value.trim();
    
    if (trimmed === "") {
        return "Unknown"
    } else {
        return trimmed
    }
}

And then we can add the console output:

function normalizeName(value) {
    if (typeof value === "object" || typeof value === "undefined") {
        return "Unknown"
    }
        
    const trimmed = value.trim();
    
    if (trimmed === "") {
        return "Unknown"
    } else {
        return trimmed
    }
}

console.log(normalizeName(" Ada "));

And we'll get the desired output:

Ada

Sorry for the 8-mile long comment, but I hope it's helpful. If you go through each of the functions slowly one by one like this, I'm sure you can fix them. You just need to be more careful and precise about what the instructions are asking for, and log only exactly what they've asked you to log.

2

u/katekatie1776 5d ago

This is beyond helpful! I really appreciate you taking the time to give me all the info. One of the issues I am running into is that some of the things they are asking me to do, such as trim(), they have not covered yet in the course. So I was googling a lot, and it seems Google led me very far astray. Do you have any suggestions for learning more efficiently?

2

u/softgray 5d ago edited 5d ago

I'm glad it helped!

MDN is a good resource when you encounter a function you don't recognize; it gives a concise explanation of what it does and some examples. It has an entry for every function and syntax in Javascript.

For example, if you searched for "trim," you'd land on this page:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim

And you can use their demo console to test out your own examples too.

I actually did this certificate myself a while back to put on my resume, though I already knew JS at the time. And to be honest, it's not very well written and often has weird evaluations like this, where they ask about things there's no way you could know about just from their material.

Depending on your motivation for doing this course (are you just trying to learn, or do you want the certificate itself?), it might be worthwhile to look at other resources for learning JS. I've heard the Odin Project is good, for one.

You could also learn JS elsewhere and then come back and breeze through the certificate once you already know it, without getting tripped up by the things Meta didn't actually teach you 😅

2

u/katekatie1776 1d ago

Thanks for the information. I'm trying to get the cert to hopefully get into development. When I did the research beforehand, everything I read was like you need to know JavaScript first. I don't work in the field currently and am wanting a career change. I have gone to YouTube, and I understand the functions separately, but applying them to this set of data just totally threw me. I have been stuck on this assignment for nearly a month now. Odin Project sounds familiar I will check that out. Thank you again. :)

2

u/nian2326076 1d ago

Make sure you're closely following the assignment requirements, as even small deviations can lead to the same grade. Break down the task into smaller parts and focus on each function one at a time. Also, you can use LandOffer to explore job opportunities related to your new skills, which may help you stay motivated in your learning.

1

u/katekatie1776 1d ago

Thank you!! I have not heard of that.

2

u/Discordbothost 6d ago

The summary repeats the averaging logic, so fixing averageScore alone leaves the summary wrong. Test buildUserSummary with Grace first. Her empty scores should give scoreCount 0 and avg null. Use the same scores array for the count and the average.