Data shapes · 11 min · free lesson

Objects and Map vs HashMap

Plain objects used as dictionaries become HashMap<K, V>: typed keys, no prototype keys, and entry for update-or-insert in one lookup.

Core idea

entry(key).or_insert(default) looks the key up once and returns a mutable reference to the value, whether or not it was already there.

JavaScript (Node.js) and Rust, side by side

JavaScript (Node.js) An object used as a dictionary: "" becomes a key, and constructor collides with Object.prototype.
function countWords(text) {
  const counts = {};
  for (const word of text.split(" ")) {
    counts[word] = (counts[word] || 0) + 1;
  }
  return counts;
}

console.log(countWords("to be or not to be"));
console.log(countWords("a  b"));        // "" became a key
console.log(countWords("constructor")); // inherited from Object.prototype
Rust split_whitespace drops empty words, entry updates in one lookup, and constructor is just another key.
use std::collections::HashMap;

fn count_words(text: &str) -> HashMap<&str, u32> {
    let mut counts = HashMap::new();
    for word in text.split_whitespace() {
        *counts.entry(word).or_insert(0) += 1;
    }
    counts
}

fn main() {
    let counts = count_words("to be or not to be");
    println!("{} {}", counts["to"], counts.get("not").copied().unwrap_or(0));
    println!("{:?}", count_words("a  b").get(""));
    println!("{:?}", count_words("constructor"));
}
What changes
JavaScript (Node.js)Rust
Object keys are strings, and "constructor" already exists on the prototype.A HashMap<&str, u32> contains only inserted keys, all of one declared type.
map.set(k, (map.get(k) ?? 0) + 1) looks the key up twice.*map.entry(k).or_insert(0) += 1 looks it up once and updates in place.
A missing key reads as undefined.get returns None; map[key] panics when the key is missing.
Map iterates in insertion order.HashMap order is unspecified; use a BTreeMap or sort the keys for stable output.

Understand it

Objects make convenient dictionaries until a key collides with the prototype. In the JavaScript example, counts["constructor"] finds Object.prototype.constructor, so (counts[word] || 0) + 1 produces "function Object() { [native code] }1". Keys are also converted to strings, so 1 and "1" are the same key. Map fixes both problems, and HashMap<K, V> is its Rust counterpart: keys and values have declared types, and only inserted keys exist.

The counting idiom becomes the entry API. counts.entry(word) looks the key up once and returns an Entry; or_insert(0) inserts the default if the slot was vacant and returns &mut u32 in both cases, so *... += 1 updates in place. get followed by insert does two lookups, and insert alone overwrites like Map.set, which is the classic bug when porting totals.set(k, (totals.get(k) ?? 0) + v).

Reading is explicit about absence. counts.get("be") returns an Option<&u32>. counts["be"] also compiles, but it panics when the key is missing instead of returning undefined, so use indexing only for keys you know are present.

Iteration order is not insertion order. A Map preserves insertion order; a HashMap uses a randomly seeded hasher, so its order can differ between runs. Sort the keys, or use a BTreeMap for key order, when output must be stable. Splitting text differs too: split(' ') keeps the empty strings between double spaces in both languages, while split_whitespace() skips them.

The JavaScript (Node.js) habit, written in Rust

This is how the JavaScript (Node.js) version usually looks on a first attempt in Rust. Predict what rustc says before you read the explanation.

use std::collections::HashMap;

fn main() {
    let mut counts: HashMap<&str, u32> = HashMap::new();
    counts.insert("to", 2);
    let be = counts["be"];
    println!("{be}");
}

Practise this code in Playground ↗

Try it

Port the JavaScript totalsByCustomer shown at the top of solution.rs. Add each order's cents to its customer's total, using entry for the update, and return the map. Keys are case-sensitive. In the Crabrix app, open the compiler lab and complete the supplied function in solution.rs. The reading question is a separate exercise.

What success looks like: The local compiler accepts the changed solution and the separate verification harness passes every case, including repeated customers, an empty list and a constructor key. Printing a success message alone does not complete this lab.

Check your understanding

Why is *counts.entry(word).or_insert(0) += 1 preferred over get followed by insert?

Reveal the answer
  1. It keeps the keys sorted
  2. It avoids allocating the key
  3. It looks the key up once and returns a mutable reference whether or not the entry existed

or_insert returns &mut V for both the vacant and the occupied case, so one lookup covers the update.

Go deeper

Common misconception: “insert adds to the existing value, the way the JavaScript counting line does.”

insert replaces the old value and returns it as an Option<V>, like Map.set. Use entry(key).or_insert(0) and add through the returned &mut V.

  1. Read the key type: count_words returns HashMap<&str, u32>: the keys borrow slices of text, so no String is allocated per word.
  2. Follow one update: For the second "to", entry finds the occupied slot, or_insert(0) returns a &mut u32 holding 1, and += 1 makes it 2.
  3. Compare with evidence: Run it: 2 1, None for the empty key, and {"constructor": 1}. Replace split_whitespace() with split(' ') and get("") returns Some(1) for "a b".

Transfer challenge: Make count_words return a BTreeMap and print the whole map for "to be or not to be". Then explain why the HashMap version might print the same pairs in a different order on another run.

Connections

  • Array methods vs iterators: Lazy iterator pipelines
  • UTF-16 strings vs UTF-8 String: UTF-8 bytes, chars and lengths
Side-by-side comparison: the JavaScript (Node.js) version on the left, the Rust version on the right, then 4 rows naming what changes.
Objects and Map vs HashMap: the same task in JavaScript (Node.js) and in Rust, with the differences that matter.
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Objects and Map vs HashMap (courseId "rust-for-nodejs-developers", lessonId "node-map-and-objects-to-hashmap")
Link: https://crabrix.com/learn/rust-for-nodejs-developers/node-map-and-objects-to-hashmap/
Goal: entry(key).or_insert(default) looks the key up once and returns a mutable reference to the value, whether or not it was already there.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=rust-for-nodejs-developers/node-map-and-objects-to-hashmap) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.