Mapping an array to a new array with default values in JavaScript

In JavaScript, mapping an array to a new array with default values is a common task when you need to transform data while ensuring missing or invalid values are replaced with fallback values.

What is Array Mapping?

Array mapping creates a new array by transforming each element of an existing array through a callback function. The original array remains unchanged, and the new array has the same length.

const numbers = [1, 2, 3];
const doubled = numbers.map(x => x * 2);

console.log(numbers);  // Original unchanged
console.log(doubled);  // New transformed array
[ 1, 2, 3 ]
[ 4, 6, 8 ]

Using map() with Default Values

The most common approach uses the logical OR operator (||) to provide defaults for falsy values like null, undefined, or empty strings:

const data = [1, null, 3, undefined, 5, "", 0];
const withDefaults = data.map(item => item || "default");

console.log(withDefaults);
[ 1, 'default', 3, 'default', 5, 'default', 'default' ]

Using Nullish Coalescing (??)

For more precise control, use the nullish coalescing operator (??) which only replaces null and undefined:

const data = [1, null, 3, undefined, 5, "", 0];
const withDefaults = data.map(item => item ?? "default");

console.log(withDefaults);
[ 1, 'default', 3, 'default', 5, '', 0 ]

Using Array.from() with Default Values

Create arrays with default values using Array.from():

// Create array of zeros
const zeros = Array.from({length: 5}, () => 0);
console.log(zeros);

// Transform existing array
const original = [2, 4, 6];
const doubled = Array.from(original, x => x * 2);
console.log(doubled);
[ 0, 0, 0, 0, 0 ]
[ 4, 8, 12 ]

Practical Examples

Here are common scenarios for mapping with defaults:

// User data with missing fields
const users = [
    {name: "Alice", age: 25},
    {name: "Bob", age: null},
    {name: null, age: 30}
];

const normalized = users.map(user => ({
    name: user.name || "Unknown",
    age: user.age || 0
}));

console.log(normalized);
[
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 0 },
  { name: 'Unknown', age: 30 }
]

Comparison of Approaches

Method Replaces Best For
|| operator All falsy values Simple default replacement
?? operator null, undefined only Preserving 0, false, ""
Array.from() N/A Creating new arrays with defaults

Conclusion

Use map() with logical operators for transforming arrays with default values. Choose || for general defaults or ?? for precise null/undefined handling. Both approaches maintain O(n) time complexity.

Updated on: 2026-03-15T23:19:00+05:30

991 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements