CS Fundamentals Trainer · JavaScript · Security

Predict the output: counting words in a plain object versus a null-prototype object.

function countWords(text) {
  const counts = {};
  for (const w of text.split(' ')) counts[w] = (counts[w] || 0) + 1;
  return counts;
}
const counts = countWords('constructor ok');
console.log(counts.ok, typeof counts.constructor);
console.log(counts.constructor);
const safe = Object.create(null);
safe.constructor = (safe.constructor || 0) + 1;
console.log(safe.constructor, 'toString' in safe);

Difficulty: medium

Answer this question

Related questions