1.3.4 - JavaScript and client-server processing

1.3.4 - JavaScript and client-server processing

JavaScript can process form input and change a page in the browser. You will follow its procedural structures, trace visible state and outputs, and decide which work belongs on a client or a server; writing practice uses a local editor and browser.

Values, operators and conversion

JavaScript is a programming language, unlike HTML markup and CSS styling. In the examples here, let declares a variable, = assigns a value and // starts a comment. A variable declared inside a function is local to that function; a variable declared outside can be available to functions in that script. let additionally has block scope, so a variable declared inside braces belongs to that block. Older exam examples can use var, whose local scope is normally the containing function rather than the block.

Form values arrive as text. In the supplied method document.getElementById("quantity").value, the browser finds the element with that ID and reads its value. The exact input method is supplied in exam questions; the important reasoning is what happens after input is received. Number("12") converts a numeric string to a number, and String(12) converts a number to text. Math.trunc(3.8) removes the fractional part. These are accurately identified JavaScript operations, not Python int or str functions.

javascript
let raw = "12";
let amount = Number(raw);
let doubled = amount * 2;
let message = "Total: " + doubled;

The states are raw = "12", amount = 12, doubled = 24, message = "Total: 24". The + operator concatenates when text is involved: "12" + 3 gives "123", while Number("12") + 3 gives 15. Conversion changes the operation's meaning.

Arithmetic uses +, -, *, /, % for remainder and ** for exponentiation. For positive integers, OCR's 17 DIV 5 corresponds to Math.trunc(17 / 5), giving 3; 17 MOD 5 corresponds to 17 % 5, giving 2. State the positive-input assumption because negative remainders and division conventions can differ between languages. ^ is not JavaScript exponentiation. Comparisons include ==, !=, <, <=, > and >=; == can convert types, while === compares without that conversion. The examples use === with known types to avoid ambiguity. Logical AND, OR and NOT are &&, || and !.

Selection and loop boundaries

Selection chooses an action; iteration repeats one. In JavaScript, parentheses contain a condition and braces group the controlled statements. For a number already read and converted, this selection handles distinct cases:

javascript
let seats = 4;
let message;
if (seats < 1) {
  message = "No booking";
} else if (seats <= 6) {
  message = "Small group";
} else {
  message = "Contact organiser";
}

Here message becomes "Small group". The earlier false condition has already ruled out values below 1. A switch can choose from discrete values:

javascript
let day = "Tue";
let room;
switch (day) {
  case "Tue": room = 12; break;
  case "Thu": room = 8; break;
  default: room = 0;
}

The break prevents execution falling through into later cases. JavaScript does not automatically stop at each case.

For a count-controlled loop, for (let i = 0; i < 4; i++) initialises i, checks the condition before each iteration and increases i after each iteration. It visits 0, 1, 2 and 3. OCR pseudocode for i=0 to 3 includes the upper endpoint; the JavaScript condition makes that boundary explicit. while tests before the body, so it can execute zero times. do ... while tests after the body, so it executes at least once. Its condition says when to continue; OCR do ... until says when to stop. Translate by reversing the condition's meaning.

javascript
let remaining = 7;
let steps = 0;
while (remaining > 0) {
  remaining = remaining - 3;
  steps = steps + 1;
}

After each completed iteration the pairs (remaining, steps) are (4,1), (1,2), (-2,3). The next test is false. Changing the update to remaining + 3 would prevent termination for this input. A useful trace records the requested state after the same point in every iteration.

javascript
let count = 0;
do {
  count = count + 1;
} while (count < 3);

This body executes three times. To express “repeat until count is at least 3”, continue while it is less than 3. Do not paste the stopping condition unchanged.

Functions, arrays and strings

A function names reusable behaviour, takes parameters and can return a result. JavaScript uses function for both a value-returning function and a procedure-like routine that performs an action without a useful returned result. A function's local accumulator is recreated for each call.

javascript
function countReady(values) {
  let count = 0;
  for (let i = 0; i < values.length; i++) {
    if (values[i] >= 5) {
      count = count + 1;
    }
  }
  return count;
}
let result = countReady([2, 5, 8]);

Arrays are indexed from zero: indices 0, 1 and 2 hold 2, 5 and 8. The count changes from 0 to 0, then 1, then 2, so result is 2. The condition i < values.length processes the last valid index without reading a nonexistent element at values.length. An empty array causes zero iterations and returns 0. A two-dimensional arrangement can use nested arrays: let grid = [[1, 2], [3, 4]]; makes grid[1][0] equal to 3, with row and column counted from zero.

Strings have .length and zero-based positions. For let word = "Network";, word.length is 7. word.substring(1, 4) returns "etw": JavaScript's second argument is the excluded end position. OCR pseudocode's subString(start, numberOfCharacters) uses a count instead. A three-character substring beginning at position 2 is therefore word.substring(2, 5), giving "two". A language translation must preserve the meaning, not copy the arguments blindly.

For the required JavaScript exam boundary, familiarity with basic pseudocode-equivalent structures is expected, but exact minor syntax inaccuracies are not penalised. JavaScript OOP and file handling are outside this Appendix 5d requirement, as are questions in which value/reference parameter-passing differences matter. Any additional JavaScript used in a question is explained. This does not relax the syntax a real browser needs to execute a saved program.

Continue this lesson.

You’re previewing NovaLearn without an account. Create a free account to read the rest.

Create free account