Emmanuel Akinfulubi

JavaScriptArray

Get an array element safely with a default in JavaScript

Beginner · 3 min read

Data from the outside world is often not what you expect. A form can send nothing, an API can leave a list out, a user can ask for page 9 of 3. When your code reads an item from an array, it should cope with all of that and give a sensible default instead of crashing or showing "undefined" on the screen.

In this tutorial you will write pick(xs, i, fallback). It returns the item at index i, or fallback when the index is out of range or xs isn't an array at all. You will also see why the easy shortcut || gets this wrong for real values like 0. You should know if, at and how default parameters look. The rest is explained below.

Falsy values

In a condition, JavaScript treats some values as "false-ish". They are called falsy: false, 0, '' (the empty string), null, undefined and NaN. Everything else is truthy.

The || operator ("or") gives the left side if it is truthy, otherwise the right side. That makes value || fallback a common way to supply a default, and a common source of bugs:

JavaScript

console.log(0 || 99);    // 99: the real 0 was thrown away
console.log('' || 'x');  // 'x'

The ?? operator is stricter. It only falls back when the left side is null or undefined:

JavaScript

console.log(0 ?? 99);         // 0
console.log(undefined ?? 99); // 99

Checking for an array

typeof can't tell you whether something is an array, because it reports 'object' for arrays and for null:

JavaScript

console.log(typeof [1, 2]);         // 'object'
console.log(typeof null);           // 'object'
console.log(Array.isArray([1, 2])); // true
console.log(Array.isArray(null));   // false

Array.isArray is the reliable test.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

7 Read an element safely, with a fallback

easy

Write pick(xs, i, fallback) that returns the element at i, or the fallback when the index is out of range or xs is not an array at all.

Stuck? Three hints, smallest first
  1. 1. Array.isArray is the reliable test; typeof reports ‘object’ for an array.
  2. 2. Compare against undefined to decide whether to fall back — but not against a falsy check, or 0 and ‘’ would trigger it.
  3. 3. ?? falls back on null and undefined only, which is usually the behaviour you want.

Step 1: read with at()

at(i) reads the item at i, and a negative i counts from the end. Out of range, it gives undefined.

Step 1

const xs = ['a', 'b', 'c'];
console.log(xs.at(1));  // 'b'
console.log(xs.at(-1)); // 'c'
console.log(xs.at(9));  // undefined

Step 2: the tempting shortcut

The quick version swaps undefined for the fallback with ||:

Step 2

const pickLoose = (xs, i, fallback) => xs.at(i) || fallback;
console.log(pickLoose(['a', 'b'], 9, '?')); // '?'
console.log(pickLoose([0], 0, 99));         // 99, but the array holds 0
console.log(pickLoose([''], 0, 'x'));       // 'x', but the array holds ''

A stock count of 0 or a blank middle name is real data. || treats them as missing and replaces them. We need to fall back only when nothing was found.

Step 3: compare with undefined

at gives undefined when the index is out of range. So test for exactly that with ===:

Step 3

function pick(xs, i, fallback = null) {
  const value = xs.at(i);
  return value === undefined ? fallback : value;
}
console.log(pick([0], 0, 99));     // 0
console.log(pick([''], 0, 'x'));   // ''
console.log(pick(['a'], 9, '?'));  // '?'
console.log(pick([], 0));          // null

condition ? a : b is the ternary operator: it gives a if the condition is true, otherwise b. Now 0 and '' come back as they are. When no fallback is passed, the default parameter makes it null.

Step 4: refuse things that aren't arrays

Call this version with null and it crashes, because null has no at method:

Step 4

function pick(xs, i, fallback = null) {
  const value = xs.at(i);
  return value === undefined ? fallback : value;
}
try {
  pick(null, 0, 'none');
} catch (e) {
  console.log(e.constructor.name); // TypeError
}

Add the Array.isArray check as the very first line:

Step 4b

function pick(xs, i, fallback = null) {
  if (!Array.isArray(xs)) return fallback;
  const value = xs.at(i);
  return value === undefined ? fallback : value;
}
console.log(pick(null, 0, 'none'));    // 'none'
console.log(pick('abc', 0, 'none'));   // 'none'
console.log(pick(['a', 'b', 'c'], -1)); // 'c'

! means "not". If xs is not an array, we return the fallback straight away and never touch at. Even a string, which does have at, is turned away, because the function promises to read arrays.

Step 5: what pick can't tell apart

Step 5

function pick(xs, i, fallback = null) {
  if (!Array.isArray(xs)) return fallback;
  const value = xs.at(i);
  return value === undefined ? fallback : value;
}
console.log(pick([null], 0, 'none'));      // null
console.log(pick([undefined], 0, 'none')); // 'none'

A stored null comes back, because we only check for undefined. But a stored undefined looks exactly like a miss. If you ever need to tell those apart, check i in xs or the array's length instead.

The full solution

The panel has the finished pick and tries it in range, out of range, from the end, on null, and on the falsy values 0 and ''. Press Run to see each result, plus the one-line xs?.[9] ?? '?' version.

The answer

function pick(xs, i, fallback = null) {
  if (!Array.isArray(xs)) return fallback;
  const value = xs.at(i);                    // handles negative indexes for us
  return value === undefined ? fallback : value;
}

const xs = ['a', 'b', 'c'];

console.log('in range      :', pick(xs, 1));
console.log('out of range  :', pick(xs, 9, '?'));
console.log('from the end  :', pick(xs, -1));
console.log('not an array  :', pick(null, 0, 'none'));
console.log('--- a falsy element must not trigger the fallback ---');
console.log('pick([0], 0, 99)  :', pick([0], 0, 99), '<- 0 is a real value');
console.log("pick([''], 0, 'x'):", JSON.stringify(pick([''], 0, 'x')));
console.log('the one-liner     :', xs?.[9] ?? '?');

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('an in-range element comes back', pick(xs, 1), 'b');
test('out of range gives the fallback', pick(xs, 9, '?'), '?');
test('a negative index counts from the end', pick(xs, -1), 'c');
test('the default fallback is null', pick([], 0), null);
test('a non-array gives the fallback', pick(null, 0, 'none'), 'none');
test('a stored 0 is not treated as missing', pick([0], 0, 99), 0);
test('nor is an empty string', pick([''], 0, 'x'), '');
test('a stored null survives, because only undefined falls back', pick([null], 0, 'none'), null);
test('a stored undefined is indistinguishable from a miss', pick([undefined], 0, 'none'), 'none');

The line to get right is value === undefined. Writing value || fallback would replace a stored 0, '' or false with the fallback, and the assertions for pick([0], 0, 99) and pick([''], 0, 'x') are there to catch exactly that.

The honest limitation is the last assertion: an array that really contains undefined cannot be told apart from one that is too short. If that distinction matters, return a { found, value } pair or test i in xs instead.

Common mistakes

  • Using || for the fallback. It replaces 0, '' and false. Compare with undefined, or use ??.
  • Using typeof xs === 'object' to check for an array. That is also true for null and plain objects. Use Array.isArray.
  • Checking the index by hand and forgetting negatives. i < xs.length lets -1 through, and xs[-1] is undefined. at handles negative indexes for you.

Try it yourself

  1. Use pick to read the third item of ['red', 'green'] with the fallback 'none'.
  2. Write pickFound(xs, i) that returns { found: true, value } or { found: false }, using i in xs for non-negative indexes.
  3. Rewrite the last two lines of pick with ??. Which results change?

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.