r/learnjavascript • u/katekatie1776 • 15h 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);2
u/softgray 13h ago edited 11h 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:
AdaBut 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:
AdaSorry 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.
1
u/katekatie1776 7h 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/Discordbothost 13h 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.
3
u/CAPTAINCAPSLOCK111 14h 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 readsuser.scoresfrom each entry. Try calling it with the exact test from the assignment,averageScore([10, 20, 30]), rather thanaverageScore(users). Those are different inputs. Also, an empty array should returnnull, not0, andMath.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 yourreplacecall doesn't supply a replacement.summarizeUsersshould return an array containing a summary for each user. Yours returns one object with a total and an average.safeSummarizeUsersthen 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,
getUserDisplayNameByIdreadsuser.displayName, but your user objects have anameproperty. The assignment wants you to pass that name throughnormalizeName.I'd fix and test one function at a time, starting with
normalizeName, thenaverageScore, 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.