Range Over Built in JavaScript

Using range to iterate over elements in various built-in data structures. Let’s see how to use range with some of the data structures we’ve already learned.

Here we use range to sum the numbers in a slice. Arrays work like this too.

let nums = [2, 3, 4];
let sum = 0;
for (let num of nums) {
    sum += num;
}
console.log("sum:", sum);

range on arrays and slices provides both the index and value for each entry. Above we didn’t need the index, so we ignored it. Sometimes we actually want the indexes though.

for (let [i, num] of nums.entries()) {
    if (num === 3) {
        console.log("index:", i);
    }
}

range on map iterates over key/value pairs.

let kvs = { "a": "apple", "b": "banana" };
for (let [k, v] of Object.entries(kvs)) {
    console.log(`${k} -> ${v}`);
}

range can also iterate over just the keys of a map.

for (let k of Object.keys(kvs)) {
    console.log("key:", k);
}

range on strings iterates over Unicode code points. The first value is the starting byte index of the character and the second the character itself.

for (let [i, c] of Array.from("go").entries()) {
    console.log(i, c.charCodeAt(0));
}

To run the program, you can simply execute it in a JavaScript runtime environment like Node.js.

$ node script.js

Expected Output:

sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
0 103
1 111