---
title: "Initialize a JavaScript Map value only when a key is missing"
url: https://recursiveai.org/oneecma/cookbook/initialize-javascript-map-value-on-demand/
description: "Initialize a JavaScript Map value only when the key is missing. Run getOrInsertComputed in C# and count initializer calls on hits and misses."
version: "1.1.1"
---

# Initialize a JavaScript Map value only when a key is missing

**OneEcma** is a free, open-source JavaScript interpreter for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneEcma) · [GitHub](https://github.com/recursive-ai-oss/oneecma-csharp) · [Docs](https://recursiveai.org/oneecma/docs/) · [Download example (.zip)](https://recursiveai.org/oneecma/cookbook/initialize-javascript-map-value-on-demand/initialize-javascript-map-value-on-demand.zip)

`getOrInsertComputed()` runs your function only for a missing key.

```shell
dotnet add package RecursiveAI.OneEcma
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using RecursiveAI.OneEcma;
var engine = new ScriptEngine();
Console.WriteLine(engine.Evaluate("""
const labels = new Map(); let calls = 0;
const get = () => labels
  .getOrInsertComputed('tea', () => ++calls);
`${get()}, ${get()}; calls: ${calls}`;
""").AsString);
```

Unzip [the example](https://recursiveai.org/oneecma/cookbook/initialize-javascript-map-value-on-demand/initialize-javascript-map-value-on-demand.zip), then `dotnet run`.

Prints the same value twice, with just one initializer call:

```text
1, 1; calls: 1
```

## The full program

The download starts with `tea` already in the map and looks up `coffee` twice. The count shows exactly which lookup calls the initializer.

```csharp
using RecursiveAI.OneEcma;

var engine = new ScriptEngine();
Console.WriteLine(engine.Evaluate("""
const labels = new Map([['tea', 'Tea']]);
let calls = 0;
const makeLabel = key => {
  calls++;
  return key.toUpperCase();
};
const lines = [];
for (const key of ['tea', 'coffee', 'coffee']) {
  const value = labels.getOrInsertComputed(key, makeLabel);
  lines.push(`${key}: ${value} (initializer calls: ${calls})`);
}
lines.push(`entries: ${labels.size}`);
lines.join('\n');
""").AsString);
```

```text
tea: Tea (initializer calls: 0)
coffee: COFFEE (initializer calls: 1)
coffee: COFFEE (initializer calls: 1)
entries: 2
```

If the initializer throws, the error propagates and `getOrInsertComputed()` does not store a result for that call.

## Variations

**Use a default value you already have.** Replace the JavaScript inside `Evaluate`:

```javascript
const counts = new Map([['tea', 3]]);
const tea = counts.getOrInsert('tea', 0);
const coffee = counts.getOrInsert('coffee', 0);
`tea: ${tea}; coffee: ${coffee}`;
```

```text
tea: 3; coffee: 0
```

## Related recipes

- [Run JavaScript in C#](https://recursiveai.org/oneecma/cookbook/run-javascript/)

## The short answer

Call `map.getOrInsertComputed(key, initializer)` when you want to compute a value only on a miss. The method passes the missing key to the initializer, stores what it returns, and returns that value to the caller. On a hit, it just returns the stored value. OneEcma includes this [ES2026 Map method](https://recursiveai.org/oneecma/docs/collections-proxy/#map-and-set). Outside OneEcma, [`getOrInsert()` and `getOrInsertComputed()`](https://github.com/mdn/browser-compat-data/blob/main/javascript/builtins/Map.json) work in Chrome and Edge 145+, Firefox 144+, Safari 26.2+, and Node.js 26.0.0+; use the [`has()`/`get()`/`set()` fallback](#whats-the-difference-between-getorinsert-and-getorinsertcomputed) below on older versions.

## How do you get a Map value by key in JavaScript?

Use [`map.get(key)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get) if you only want to read. It returns `undefined` when the key is absent, but also when you’ve deliberately stored `undefined`. Use `map.has(key)` when that distinction matters. `getOrInsertComputed()` checks for an entry, not for a truthy value: an existing `undefined`, `null`, `false`, or `0` still counts as a hit. Testing `map.get(key)` for truthiness would replace some of those values even though the key is already there.

## What’s the difference between `getOrInsert()` and `getOrInsertComputed()`?

Use [`getOrInsert()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/getOrInsert) with a value you already have, like the starting count `0` above. JavaScript evaluates arguments before calling the method, so passing the result of an initializer to `getOrInsert()` runs that initializer even on a hit. With [`getOrInsertComputed()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/getOrInsertComputed), pass the function itself. The method invokes it only when it has to insert a value.

For a runtime that doesn’t have the method, use `has()`, `set()`, and `get()`. Here’s a replacement script for the call at the top:

```javascript
const labels = new Map([['tea', undefined]]);
let calls = 0;
function get(key) {
  if (!labels.has(key)) {
    calls++;
    labels.set(key, key.toUpperCase());
  }
  return labels.get(key);
}
`${get('tea')}, ${get('coffee')}; calls: ${calls}`;
```

```text
undefined, COFFEE; calls: 1
```

The test on `has()` preserves the explicitly stored `undefined` for `tea`. Only the new `coffee` key triggers initialization.
