Checkpoint: Core JavaScript

Published by Brayan K

You've learned the this keyword, destructuring, spread/rest, map/filter/reduce, hoisting, scope and Map/Set — let's put them together.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Define the report before choosing the syntax

Build a summary of a fixed local user list. Active means the active field is exactly true. The report needs an active count, active names, an active spending total and the unique countries across all records. Spending is a nonnegative integer count of minor units in this exercise; no currency conversion or rounding policy is involved.

Those fields do not all use the same population: names and spending use active records, while countries uses every record. Keep that distinction visible in intermediate variables. The checkpoint practises choosing tools for a contract, not forcing every language feature into one function.

function summarize(users) {
  const active = users.filter(user => user.active === true);
  // Names and spending use only the selected records.
  const names = active.map(({ name }) => name);
  const totalSpent = active.reduce((sum, user) => sum + user.spent, 0);
  // Countries intentionally uses all records, including inactive ones.
  const countries = [...new Set(users.map(user => user.country))];
  return { activeCount: active.length, totalSpent, countries, names };
}
const users = [
  { name: "Mia", country: "UK", active: true, spent: 120 },
  { name: "Noah", country: "CA", active: false, spent: 900 },
  { name: "Eli", country: "UK", active: true, spent: 0 },
  { name: "Ava", country: "FR", active: true, spent: 80 }
];
console.log(JSON.stringify(summarize(users)));

// ✅ Expected output:
// {"activeCount":3,"totalSpent":200,"countries":["UK","CA","FR"],"names":["Mia","Eli","Ava"]}

map, filter & reduce owns transformation, selection and accumulation. Here, inspect which list each operation consumes rather than repeating those method definitions.

Use boundary inputs to expose a hidden assumption

A report should have a meaningful empty result. A reduction without an initial value can work on the first demonstration list and still fail as soon as no records pass the filter. Run that smaller case directly when diagnosing the failure.

const users = [{ name: "Noah", active: false, spent: 900 }];
const selected = users.filter(user => user.active === true);
const total = selected.map(user => user.spent).reduce((sum, value) => sum + value);
console.log(total);

// ✅ Expected error:
// TypeError: Reduce of empty array with no initial value
function summarize(users) {
  const active = users.filter(user => user.active === true);
  return {
    activeCount: active.length,
    totalSpent: active.reduce((sum, user) => sum + user.spent, 0),
    countries: [...new Set(users.map(user => user.country))],
    names: active.map(({ name }) => name)
  };
}
console.log(JSON.stringify(summarize([])));
console.log(JSON.stringify(summarize([
  { name: "Noah", country: "CA", active: false, spent: 900 }
])));

// ✅ Expected output:
// {"activeCount":0,"totalSpent":0,"countries":[],"names":[]}
// {"activeCount":0,"totalSpent":0,"countries":["CA"],"names":[]}

An empty active selection still leaves information about inactive countries in this report. If the product wanted countries of active users instead, that would be a different contract and a different input list for that field.

Preserve valid zero values and exact selection rules

A zero spending value is valid. Likewise, a truthy string is not automatically the boolean flag required by this exercise. The following diagnostic inspects the selection rule without pretending to validate every field of an arbitrary API response.

const records = [
  { name: "Mia", active: true, spent: 0 },
  { name: "Noah", active: false, spent: 5 },
  { name: "Eli", active: "false", spent: 9 }
];
console.log(JSON.stringify(records.filter(user => user.active).map(user => user.name)));
console.log(JSON.stringify(records.filter(user => user.active === true).map(user => user.name)));

// ✅ Expected output:
// ["Mia","Eli"]
// ["Mia"]
const records = [{ spent: 0 }, {}, { spent: 12 }];
const values = records.map(({ spent = 0 }) => spent);
console.log(JSON.stringify(values));
console.log(values.reduce((sum, value) => sum + value, 0));

// ✅ Expected output:
// [0,0,12]
// 12

Type Coercion (== vs ===) owns conversion rules, and Destructuring Assignment owns undefined-only defaults. The main report’s documented inputs already contain numeric spent fields; a default is not a substitute for validating wrongly typed or null data.

Uniqueness and sorting are separate decisions

The report preserves the first appearance of each exact country string. A Set removes duplicate values under its equality rule; it does not sort names or normalize their case. Specify those as additional requirements if a display needs them.

const countries = ["UK", "CA", "UK", "uk", "FR"];
console.log(JSON.stringify([...new Set(countries)]));

// ✅ Expected output:
// ["UK","CA","uk","FR"]

Map & Set owns membership, identity and ordering. Do not deduplicate whole user objects when the requirement is unique country identifiers.

A derived report must not edit the records it describes

Returning a new array from map is not enough if the callback assigns to the original records. Capture a before snapshot while checking a report, then compare the input after the calculation. For this fixed plain-data fixture, JSON text is a convenient observation of its fields.

const users = [{ name: "Mia", active: true, spent: 0 }];
const before = JSON.stringify(users);
const labels = users.map(user => {
  user.name = user.name.toUpperCase();
  return user.name;
});
console.log(JSON.stringify(labels));
console.log(JSON.stringify(users) === before);

// ✅ Expected output:
// ["MIA"]
// false

A read-only callback can return user.name.toUpperCase() directly. Spread & Rest Operators owns constructing changed records and the limits of shallow copies. The independent report below only reads its inputs.

Keep a formatter’s receiver when passing it into a report step

A formatting method may depend on its receiver. Passing that method directly as a callback can lose the context it needs. The this Keyword owns the receiver rules; here the failure is observed at the report’s formatting boundary.

"use strict";
const formatter = {
  prefix: "User: ",
  label(name) { return this.prefix + name; }
};
console.log(JSON.stringify(["Mia", "Eli"].map(formatter.label)));

// ✅ Expected error:
// TypeError: Cannot read properties of undefined (reading 'prefix')
"use strict";
const formatter = {
  prefix: "User: ",
  label(name) { return this.prefix + name; }
};
const label = formatter.label.bind(formatter);
console.log(JSON.stringify(["Mia", "Eli"].map(label)));

// ✅ Expected output:
// ["User: Mia","User: Eli"]

Complete three expressions in the summary

Use the literal hints to select the required records, extract their names and add their spending. The unique-country field is already supplied so the exercise has three decisions to complete.

const users = [
  { name: "Mia", country: "UK", active: true, spent: 120 },
  { name: "Noah", country: "CA", active: false, spent: 900 },
  { name: "Eli", country: "UK", active: true, spent: 0 }
];
const active = users.filter(user => user.active === ___);
const names = active.map(({ ___ }) => name);
const totalSpent = active.map(user => user.spent)
  .reduce((sum, value) => ___, 0);
const countries = [...new Set(users.map(user => user.country))];
// 👉 replace ___ with true
// 👉 replace ___ with name
// 👉 replace ___ with sum + value
console.log(JSON.stringify({ activeCount: active.length, names, totalSpent, countries }));

// ✅ Expected output:
// {"activeCount":2,"names":["Mia","Eli"],"totalSpent":120,"countries":["UK","CA"]}

Add country totals without changing the report’s populations

Write summarize(users) with the original four report fields, then add byCountry: an array of country/total pairs for active users only, in first-active-occurrence order. Use exact country strings, preserve zero totals, and leave every input record unchanged. Check a mixed list, an empty list and an all-inactive list. Inputs contain string names/countries, boolean active flags and nonnegative integer spending values.

function summarize(users) {
  const active = users.filter(user => user.active === true);
  const byCountry = new Map();
  for (const { country, spent } of active) {
    const previous = byCountry.has(country) ? byCountry.get(country) : 0;
    byCountry.set(country, previous + spent);
  }
  return {
    activeCount: active.length,
    totalSpent: active.reduce((sum, { spent }) => sum + spent, 0),
    countries: [...new Set(users.map(({ country }) => country))],
    names: active.map(({ name }) => name),
    byCountry: [...byCountry]
  };
}
const users = [
  { name: "Mia", country: "UK", active: true, spent: 0 },
  { name: "Noah", country: "CA", active: false, spent: 900 },
  { name: "Eli", country: "FR", active: true, spent: 80 },
  { name: "Ava", country: "FR", active: true, spent: 20 }
];
const before = JSON.stringify(users);
console.log(JSON.stringify(summarize(users)));
console.log(JSON.stringify(summarize([])));
console.log(JSON.stringify(summarize([users[1]])));
console.log("input unchanged", JSON.stringify(users) === before);

// ✅ Expected output:
// {"activeCount":3,"totalSpent":100,"countries":["UK","CA","FR"],"names":["Mia","Eli","Ava"],"byCountry":[["UK",0],["FR",100]]}
// {"activeCount":0,"totalSpent":0,"countries":[],"names":[],"byCountry":[]}
// {"activeCount":0,"totalSpent":0,"countries":["CA"],"names":[],"byCountry":[]}
// input unchanged true

The country totals are converted to entry pairs deliberately; serializing a Map directly would not expose its collection entries as this report expects. If your result differs, inspect active first, then the accumulator and finally the output fields. A single final total cannot show which stage selected the wrong records.

For the underlying contracts, revisit map, filter & reduce, Map & Set and Destructuring Assignment. The checkpoint owns combining them and checking the report, not redefining those language features.

Practice quiz

What does this complete program print? const users = [{ active: true, spent: 0 }, { active: false, spent: 9 }]; const active = users.filter(user => user.active === true); console.log(active.length, active.reduce((sum, user) => sum + user.spent, 0));

  • 1 0
  • 0 0
  • 1 9
  • 2 9

Answer: 1 0. The active record still counts when its spending is zero.

What does this complete program print? const users = [{ country: "UK", active: true }, { country: "CA", active: false }]; console.log(JSON.stringify([...new Set(users.map(user => user.country))]));

  • ["UK"]
  • ["UK","CA"]
  • ["CA"]
  • []

Answer: ["UK","CA"]. This field uses all users, so the inactive record’s country remains included.

Which error ends this program? console.log([].reduce((sum, value) => sum + value));

  • ReferenceError: sum is not defined
  • TypeError: sum is not a function
  • TypeError: Reduce of empty array with no initial value
  • RangeError: Invalid array length

Answer: TypeError: Reduce of empty array with no initial value. An empty selected group has no first accumulator when the initial value is omitted.

What does this complete program print? const users = [{ name: "Mia" }]; const names = users.map(user => { user.name = "Changed"; return user.name; }); console.log(users[0].name);

  • Mia
  • undefined
  • TypeError: Assignment to constant variable.
  • Changed

Answer: Changed. The callback assigns to the original record despite map creating a new outer array.

What does this complete program print? const { spent = 5 } = { spent: 0 }; console.log(spent);

  • 0
  • 5
  • undefined
  • null

Answer: 0. The default is not used for an existing zero value.

What does this complete program print? console.log(JSON.stringify([...new Set(["FR", "UK", "FR", "fr"])]));

  • ["FR","UK"]
  • ["FR","UK","fr"]
  • ["FR","fr","UK"]
  • ["UK","FR","fr"]

Answer: ["FR","UK","fr"]. Set preserves first occurrence and treats differently cased strings as distinct values.

What does this complete program print? "use strict"; const formatter = { prefix: "User: ", label(name) { return this.prefix + name; } }; const label = formatter.label.bind(formatter); console.log(label("Mia"));

  • Mia
  • undefinedMia
  • User: Mia
  • TypeError: label is not a function

Answer: User: Mia. The bound callback retains the formatter object as its receiver.

What does this complete program print? const totals = new Map([["UK", 0], ["FR", 80]]); console.log(JSON.stringify([...totals]));

  • {}
  • [0,80]
  • ["UK","FR"]
  • [["UK",0],["FR",80]]

Answer: [["UK",0],["FR",80]]. Spreading a Map produces entry pairs suitable for this report’s explicit output shape.

Continue this course

Related lessons