Pure Functions & Immutability — Series 2

Preview — 3 of 10 questions

Which of the following best describes a pure function?

AA function that, given the same inputs, always returns the same output and produces no observable side effects
BA function that always returns undefined
CA function that only accepts a single argument
DA function declared with the function keyword rather than as an arrow function

What is logged, and is addToTotal a pure function?

javascript
let total = 0;

function addToTotal(n) {
  total += n;
  return total;
}

console.log(addToTotal(5));
console.log(addToTotal(5));
A5, 5 — pure, since it always returns 5 for the input 5
B5, 10 — not pure, because it mutates and depends on external state
C5, 10 — still pure, since it only reads total internally
D10, 10 — pure

What is logged?

javascript
const numbers = Object.freeze([1, 2, 3]);

try {
  numbers.push(4);
} catch (e) {
  console.log(e instanceof TypeError);
}

console.log(numbers.length);
console.log(numbers);
Afalse, 4, [1, 2, 3, 4]
Bfalse, 3, [1, 2, 3]
Ctrue, 3, [1, 2, 3]
Dtrue, 4, [1, 2, 3, 4]

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.