Zum Inhalt springen

English:Developing and testing a JavaScript data application - Computing Year 9

Aus MOOCsWiki Staging
aiMOOC-Siegel aiMOOC

Developing and testing a JavaScript data application - Computing Year 9

QR-Code



Introduction

Create and test an original JavaScript event-capacity checker with exactly three inputs,explicit validation,array operations and clear feedback. Complete the required maximum18 example and reject empty fields. Year9 is an editorial allocation in England’s KS3 Computing progression.


Specify inputs,validation and meaningful output


Specify the data contract and visible result

A data application has a chain of responsibilities: collect entries, validate their representation, convert accepted values, perform an operation and show feedback. A browser page does not make its input automatically trustworthy. A result is useful only when the calculation, accepted data and stated purpose agree. For this course, all event-capacity values are invented classroom data, not verified limits for a real venue.

The required application accepts exactly three fields. Each trimmed field must contain one to four ordinary decimal digits and represent a whole number from 0 to 1000. Zero is a valid value; an empty field is not zero. Fractions, negative signs, exponential notation and nonnumeric text are rejected. Leading zeros are accepted within the four-digit spelling limit and converted numerically. These are explicit teaching choices, not universal restrictions on JavaScript or every capacity system.

The required output is the largest accepted value. Our original extension also identifies every option tied for that value, the sum of entries and a separately sorted numeric copy. A sum of fictional capacities is arithmetic, not authorisation to combine real spaces or a statement about safe occupancy. Keep that distinction visible without asking learners for any real school data.

Input entries Expected main result Reason
12,18,9 Largest18;option 2 The required normal case
18,18,9 Largest18;options 1 and2 A tie should not disappear
0,0,0 Largest0;all three options Zero is explicitly permitted
12, empty,9 Validation message for option 2 Missing data must not silently become zero
12, hello,9 Validation message for option 2 Text has not supplied a whole number
12,1001,9 Validation message for option 2 The teaching bound is1000

Validation checks shape and allowed range, not whether a capacity was measured correctly or approved by an authorised person. If a future app uses real information, its source, permissions, updates and server-side checks need their own design. This exercise instead makes a complete local data flow visible and testable without accounts, network requests or personal data.

Programming with Mosh: JavaScript beginner course. Use its language overview for arrays, functions and events;the thumbnail’s one-hour slogan is not a promise of mastery or the time required for this project. Original: Programming with Mosh, JavaScript Course for Beginners – Your First Step to Web Development. The written explanations and native tasks work without sound or the external player.

Before writing the interface, describe what the calculation function should accept and return. Keeping that core separate makes it possible to test hundreds of inputs without clicking through the page. The later interface tests answer a different question:whether users can trigger the right calculation and receive clear feedback.



Build the complete original data application


Convert only after checking the spelling

JavaScript Number can convert an empty string to zero, which would violate this application's required empty-field rule. The core therefore trims each string and checks its complete decimal spelling before conversion. The regular expression rejects empty text, decimal points, letters and exponent markers. Then the numeric check enforces the 0 to 1000 bound. A numeric keyboard hint helps entry but is not itself validation.

The three accepted numbers form an array. Math.max examines those values to find the largest;map and filter identify every matching option number;reduce calculates the sum using an explicit initial zero. A copied array is sorted numerically with a subtraction comparator. The original option order remains available for labels and results. JavaScript's default string-like sort order would not put[12,18,9]in the intended numeric order[9,12,18].


Complete original JavaScript application

Run the following complete script in a school-approved empty HTML preview that supports JavaScript, or attach it to a new blank practice HTML file. It creates its own labelled interface. Do not paste scripts into the console of a signed-in service or change a live portal page. The app has no external dependency and makes no network or storage call. It is an executable practice artefact, not an installed MOOCwiki administration tool.

function evaluateCapacities(raws) {
  const invalid = index => ({ok: false, index,
    message: "Enter a whole decimal capacity from 0 to 1000 in each field."});
  if (!Array.isArray(raws) || raws.length !== 3) return invalid(0);
  const values = [];
  for (let i = 0; 3 > i; i += 1) {
    if (typeof raws[i] !== "string") return invalid(i);
    const text = raws[i].trim();
    if (!/^[0-9]{1,4}$/.test(text)) return invalid(i);
    const value = Number(text);
    if (!Number.isInteger(value) || !(value >= 0 && 1000 >= value)) return invalid(i);
    values.push(value);
  }
  const largest = Math.max(...values);
  const options = values.map((value, i) => value === largest ? i + 1 : null)
                        .filter(value => value !== null);
  return {ok: true, values, largest, options,
          total: values.reduce((sum, value) => sum + value, 0),
          ordered: values.slice().sort((a, z) => a - z)};
}

(() => {
  const el = (tag, text) => {
    const node = document.createElement(tag);
    if (text !== undefined) node.textContent = text;
    return node;
  };
  const root = el("main");
  Object.assign(root.style, {maxWidth: "44rem", margin: "1rem auto", padding: "1rem", boxSizing: "border-box", fontFamily: "system-ui, sans-serif", color: "#17364b", overflowWrap: "anywhere"});
  root.append(el("h1", "Event capacity checker"), el("p", "Practice with three invented capacities. Whole decimal values from 0 to 1000; zero is allowed. This classroom calculation is not a venue safety or occupancy decision."));
  const form = el("form");Object.assign(form.style, {display: "grid", gap: "0.8rem"});
  const fields = el("div");Object.assign(fields.style, {display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(12rem, 1fr))", gap: "0.8rem"});
  const inputs = [], errors = [];
  for (let i = 0; 3 > i; i += 1) {
    const group = el("div");Object.assign(group.style, {display: "grid", gap: "0.4rem"});
    const label = el("label", "Option " + (i + 1) + " capacity");
    const input = el("input");input.id = "capacity-" + (i + 1);input.type = "text";input.inputMode = "numeric";input.maxLength = 8;input.autocomplete = "off";label.htmlFor = input.id;
    const error = el("p", "");error.id = "error-" + (i + 1);error.style.margin = "0";error.style.color = "#a02020";
    input.setAttribute("aria-describedby", error.id);input.setAttribute("aria-invalid", "false");
    Object.assign(input.style, {width: "100%", minHeight: "44px", boxSizing: "border-box", fontSize: "1rem"});
    inputs.push(input);errors.push(error);group.append(label, input, error);fields.append(group);
  }
  const check = el("button", "Check capacities");check.type = "submit";
  const clear = el("button", "Clear");clear.type = "button";
  for (const button of [check, clear]) Object.assign(button.style, {minHeight: "44px", fontSize: "1rem", padding: "0.5rem"});
  const result = el("p", "Enter three capacities, then choose Check capacities.");result.id = "capacity-result";result.setAttribute("role", "status");result.setAttribute("aria-live", "polite");
  const list = el("ul");list.id = "capacity-values";
  function resetFeedback(message) {
    for (let i = 0; 3 > i; i += 1) {inputs[i].setAttribute("aria-invalid", "false");errors[i].textContent = "";}
    result.textContent = message;list.replaceChildren();
  }
  for (const input of inputs) input.addEventListener("input", () => resetFeedback("Values changed. Check capacities again."));
  form.addEventListener("submit", event => {
    event.preventDefault();resetFeedback("");
    const answer = evaluateCapacities(inputs.map(input => input.value));
    if (!answer.ok) {
      result.textContent = answer.message;errors[answer.index].textContent = "Check this field: use 0 to 1000 whole decimal units.";
      inputs[answer.index].setAttribute("aria-invalid", "true");inputs[answer.index].focus();return;
    }
    result.textContent = "Largest capacity: " + answer.largest + "; option numbers: " + answer.options.join(", ") + "; sum of input values: " + answer.total + ". Numeric order: " + answer.ordered.join(", ") + ".";
    answer.values.forEach((value, i) => list.append(el("li", "Option " + (i + 1) + ": " + value + (answer.options.includes(i + 1) ? " - largest" : ""))));
  });
  clear.addEventListener("click", () => {
    for (const input of inputs) input.value = "";
    resetFeedback("Enter three capacities, then choose Check capacities.");inputs[0].focus();
  });
  form.append(fields, check, clear, result, list);root.append(form, el("p", "Results belong only to the current entries. Nothing is sent, saved or awarded as learning points; refreshing resets the prototype."));document.body.append(root);
})();

For the required[12,18,9]case, the values array is[12,18,9], largest is18, options is[2], total is39 and ordered is[9,12,18]. The stored index is zero-based inside the map, while the visible option numbers add one. A learner should be able to explain why returning index1 alone would be ambiguous to someone who sees Option2 on the screen.

The core returns either a successful structured result or an error with the first invalid field's index. An invalid result contains no largest value that could be mistaken for a fresh calculation. The interface clears previous results before displaying an error. Editing any field also marks the old result as stale and removes its list, so an old maximum is not silently left beside new data.

The form's submit event handles both ordinary button activation and keyboard submission. preventDefault keeps the local practice page from navigating away. The Clear button deliberately uses type button so it does not submit by accident. It clears fields and feedback and moves focus to the first field. A visible label and a field-specific error support understandable correction.

HTML5 logo as context for labelled form structure
The unchanged W3C HTML5 logo represents semantic page structure. The application uses labels,inputs,buttons and a status region;the logo does not certify its accessibility or correctness.
CSS3 logo as context for responsive presentation
The unchanged Rudloff CSS3 logo represents presentation. The layout keeps controls readable and usable across the tested widths;visual styling does not validate the entered data.

The source builds elements and assigns plain text through textContent. Accepted capacities become numbers;raw entries are never interpreted as HTML. This supports a safe rendering boundary, while a future networked application would still need its own authorisation, validation and persistence design. A pleasant button or a correctly computed maximum does not remove those separate responsibilities.



Test calculations,interaction and remaining limits


Plan tests before accepting the screen

Separate core calculation tests from interface tests. For the core, provide exact strings and compare every returned field with an independent expected result. Include ties, all zeros, one maximum at each position, range endpoints, leading zeros and invalid spellings. Check that the input array is preserved. A passing screenshot does not establish that these cases work.

For the interface, exercise the real labels and buttons. Try the required values, then change one field and confirm that stale feedback is removed before checking again. Try an empty or invalid middle field and confirm that it is identified, receives focus and does not retain an old maximum. Press Enter to submit, activate the button by keyboard and try touch on a narrow layout. Record the actual browser/setup and results rather than claiming universal device support.

Test group Exact example Expected evidence
Normal 12,18,9 Largest18, option 2, total 39, order9,12,18
Tie 18,18,9 Options1 and2 both identified
Lower bound 0,0,0 Valid largest 0 and all options tied
Upper bound 1000,0,9 Valid largest 1000 and total 1009
Empty 12, blank,9 No numeric result;first invalid index1
Spelling 12,1e2,9 Rejected by the declared decimal-only rule
State change Change18to8after a successful check Old summary/list cleared until a new check
Clear Activate Clear after a result All fields empty;initial feedback and first-field focus

Exact test data are important. Whitespace around an accepted value is trimmed, but whitespace alone is missing data. A string such as0009 is accepted as nine;2.5is rejected even though JavaScript can represent it. The chosen contract does not need to accept every expression that Number could evaluate. Never use eval to turn a text field into a calculator for this task.


Interpret limits and improve deliberately

Three fields make the scope clear and allow a complete independent check. If the task later accepts an arbitrary list, the empty-array case, limits, editing, ordering and labels need new decisions. Math.max on an empty argument list would not supply a legitimate capacity;the present core avoids that problem by requiring exactly three valid entries. Do not broaden the interface and silently retain assumptions that only fit three fields.

User-facing feedback should state what was accepted or rejected. The first-invalid-field approach helps a learner make one correction at a time, but it does not claim that every other field was already checked successfully. A more advanced interface could show all errors together, provided it preserves clear labels and predictable focus. Changing the error design requires fresh tests rather than only a new colour.

The native MOOC exercises supply practice and assessment alongside this code. The local app itself writes no MOOCwiki learning points and does not prove that a learner understands arrays. Ask the learner to explain the data transformation, predict a tie and justify the empty-input rule. A correct copied result is different from a reasoned demonstration.

Submit the complete working artefact, its data contract, a normal/boundary/invalid test table, and evidence of actual keyboard/touch checks where performed. Include one clearly labelled improvement and a retest plan. Acknowledge untested browsers, assistive technologies and known-user arrangements;an automated local test is not a classroom user study or independent accessibility certificate.



Interactive Tasks


Quiz: Test Your Knowledge

What is the required largest value for[12,18,9]? (18) (!12) (!9) (!39)



Why is an empty field checked before Number conversion? (Number can turn an empty string into zero,violating this contract) (!Every empty string is a measured zero capacity) (!An empty field automatically contains the previous value) (!Number always throws for whitespace)



Which input is allowed by the declared rule? (0009 representing nine) (!2.5 as a fractional capacity) (!1e2 as exponential notation) (!An empty field)



What should[18,18,9]report? (Largest18 with options1 and2) (!Only the final option regardless of value) (!No result because all ties are invalid) (!A total capacity approval for a real building)



What is the numeric sorted copy of[12,18,9]? (9,12,18) (!12,18,9) (!18,12,9) (!39)



Why keep a copied array for sorting? (Preserve original option order while presenting an ordered view) (!Remove every duplicate value) (!Make invalid data automatically valid) (!Avoid all later tests)



What should happen after a value is edited? (Mark the previous result stale and require a new check) (!Leave an old maximum looking current) (!Award points for every keystroke) (!Send the unfinished entry to an external server)



Which control action should submit the local form? (The submit button or appropriate keyboard submission) (!Clear because every button must submit) (!Every focus change automatically) (!Loading a logo image)



What does a zero maximum for[0,0,0]mean here? (A valid arithmetic result under the declared zero-allowed contract) (!Every real venue is approved for an event) (!Input validation was skipped) (!An empty string was intentionally treated as data)



What is established by successful local interface tests? (Evidence for the exact tested cases,browser and setup) (!Universal accessibility certification) (!Proof of every learner’s understanding) (!Authorisation to change real occupancy arrangements)





Memory Game

Validation Check the accepted representation and range
Array An ordered collection of values
Maximum The greatest accepted value
Comparator A rule defining the intended sort order
Feedback Information about accepted input,result or correction
Stale result An answer that no longer matches current entries





Drag and Drop

An empty entry becomes numeric0 Validate the spelling before conversion
Two options share the largest value Preserve and identify both matching options
Default sorting puts12before9 Use an explicit numeric comparator
New entries sit beside an old maximum Clear stale feedback until the next valid check
A successful calculation is called venue approval Separate arithmetic practice from authorised real-world decisions





Crossword Puzzle

ARRAY What ordered structure stores the accepted capacities?
MAXIMUM What is the greatest accepted capacity?
INPUT What does a learner enter before calculation?
VALIDATION What checks spelling and allowed range?
FEEDBACK What explains the result or needed correction?
COMPARATOR What specifies numeric sorting order?





LearningApps

Optional extra practice. Choose an appropriate activity with your teacher. If the external collection is unavailable, use the native activities and independent tasks in this course.


Cloze Text

Complete the explanation.
Collect exactly three

. Reject an empty field before numeric

. Store accepted values in an

. Find the greatest value,the

. Preserve every matching option in a

. A numeric sort needs a

. Editing makes the old result

. Use clear field-specific

. A keyboard submit triggers the form

. Tests supply bounded

.



Open Tasks


Easy

  1. Complete the required example: Predict largest,matching option,total and numeric order for12,18,9.
  2. Distinguish zero from empty: Explain the different outcomes for0and a blank field.
  3. Predict a tie: Find every largest option for18,18,9 and0,0,0.
  4. Explain one array operation: Describe how map,filter,reduce or numeric sorting supports the visible output.


Standard

  1. Build the required capacity checker: Run the full original script in an approved empty practice preview and demonstrate three-field input and largest output.
  2. Test invalid inputs: Create an expected/actual table for blank,whitespace,text,fractional,negative and over-bound entries.
  3. Exercise the interface: Test Enter,button activation,Clear,stale-result clearing and first-invalid-field focus.
  4. Check responsive use: Try a narrow layout and touch where available;record the actual setup and limits.


Advanced

  1. Separate unit and interface evidence: Explain which tests establish calculations and which establish event handling and feedback.
  2. Challenge numeric conversion: Compare the declared digit-only contract with other strings Number can convert and justify the restriction.
  3. Plan a variable-length extension: Define empty-list,length,editing,tie and ordering behaviour before changing the three-field app.
  4. Evaluate for a known user: Plan a voluntary school-approved test with invented data and propose one evidence-led revision without inventing results.



Learning Check

  1. Required output: Analyse12,18,9under the declared contract.
  2. Empty rejection: Explain why12,blank,9must not produce a maximum.
  3. Tie and boundary: Give results for18,18,9and0,0,0.
  4. Numeric order: Explain the ordered-copy operation.
  5. Interaction state: State what editing and Clear should do after a valid result.
  6. Honest evaluation: Distinguish calculation tests,interaction tests and learner evidence.


Worked checks and assessment guidance

  1. Accepted numbers[12,18,9];largest18;visible option2;sum39;numeric ordered copy[9,12,18]. Original option order stays available. This is fictional arithmetic,not approval of a real venue.
  2. The blank field fails the digit-spelling check before Number conversion. Return an invalid result at index1,show a clear option2 error,focus that field and remove stale output. Do not silently interpret it as zero.
  3. The first case has largest18and options1,2,total45. The second is valid with largest0,options1,2,3,total0. All tied options are retained. Exactly1000is allowed;1001is rejected.
  4. Make a copy of the accepted values and use a numeric subtraction comparator;the required order is9,12,18. The original position/value mapping is preserved. Default string ordering is not the numeric contract.
  5. Editing clears the old summary/list and requests another check. Clear empties all fields,restores initial feedback and focuses the first field without submitting. Enter and the submit button use the same prevented-default form handler.
  6. Pure tests compare structured results with independent expectations. DOM tests exercise actual controls,focus and feedback in a stated browser. Neither alone proves a known user can complete every task or a learner understands the code;explanations and appropriate user evidence remain necessary.


Learning evidence

Keep the complete original artefact,data contract,expected/actual calculation cases,normal/boundary/invalid interface cases and actual keyboard/touch setup. Explain ties,numeric sorting,zero versus empty and stale feedback. Identify one remaining limit and justified improvement without claiming real event approval or a classroom trial.


OER and Wikipedia

MDN: Array, MDN: textContent, MDN: form submit event;language and platform behaviour,not copied application code. DfE: KS3 Computing programme;editorial Year9 allocation. Primary references reviewed14November2026. All input cases,complete application code,activities and assessments are original.

HTML5 logo and wordmark.svg, W3C, CC BY 3.0. Unchanged original; caption and learning activities are original.

CSS3 logo and wordmark.svg, Rudloff, CC BY 3.0. Unchanged original; caption and learning activities are original.


Linked learning areas


aiMOOC Projects



Schulfach+




aiMOOCs



aiMOOC Projekte









MOOCwiki · Deutsch

Nach dem Lernen ist vor dem Lernen

Entdecke direkt den nächsten Lernkurs. Weitere Inhalte erscheinen, wenn Du weiter nach unten scrollst.

Zur MOOCwiki-Hauptseite

Mediathek

Suche verfeinern

Dein Lernplan bestimmt, was oben steht. Alle anderen Inhalte bleiben erreichbar. Seitenaufrufe beeinflussen die Auswahl nicht.

Inhalte werden geladen ...

Mediathek wird aus dem Wiki geladen ...