Type Checks With typeof And Array.isArray

Guard untrusted JSON values with typeof plus a null check, then separate arrays from plain objects with Array.isArray because typeof reports both as object.

JavascriptSecurity Boundaries

Code

javascriptsnippet
27 lines
// Runtime type checks for values that come back from JSON payloads
const samples = [
  ['null', null],
  ['undefined', undefined],
  ['number', 42],
  ['NaN', NaN],
  ['string', 'text'],
  ['boolean', true],
  ['array', []],
  ['object', {}],
  ['function', () => {}],
  ['bigint', 10n],
];

for (const [label, value] of samples) {
  const kind = value === null ? 'null' : typeof value;
  console.log(label.padEnd(10), 'typeof =', kind.padEnd(10), 'Array.isArray =', Array.isArray(value));
}

// typeof null 报告 'object' 是历史遗留:先挡空值,再用 Array.isArray 区分数组
function isPlainObject(value) {
  return typeof value === 'object' && value !== null && !Array.isArray(value);
}

console.log('typeof null is', typeof null, '- the guard above rejects it first');
const passed = samples.filter(([, v]) => isPlainObject(v)).map(([label]) => label);
console.log('isPlainObject passes for:', passed.join(', '));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

null       typeof = null       Array.isArray = false
undefined  typeof = undefined  Array.isArray = false
number     typeof = number     Array.isArray = false
NaN        typeof = number     Array.isArray = false
string     typeof = string     Array.isArray = false
boolean    typeof = boolean    Array.isArray = false
array      typeof = object     Array.isArray = true
object     typeof = object     Array.isArray = false
function   typeof = function   Array.isArray = false
bigint     typeof = bigint     Array.isArray = false
typeof null is object - the guard above rejects it first
isPlainObject passes for: object

What the code does

The callable surface is the function isPlainObject — everything else is wiring.

Iteration happens inside for (const [label, value] of samples) — everything outside it runs once.

Applying it

Entry signature: function isPlainObject(value)

The demo output is labeled (typeof null is, isPlainObject passes for:), so the printed lines read as a trace of the operations that ran.

Statements that matter

const passed = samples.filter(([, v]) => isPlainObject(v)).map(([label]) => label);
return typeof value === 'object' && value !== null && !Array.isArray(value);

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
No — every API used here ships with the language runtime, so there is nothing to install. The file defines `isPlainObject` at load time.