Menu
CoddyTech

Closures and Callbacks

Lesson 25 of 48 in Coddy's JavaScript for C++ Developers course.

C++ lambdas choose value or reference captures explicitly, and references must not outlive their referents. JavaScript closures retain lexical bindings after the creator returns. let declarations in a loop provide separate iteration bindings. Passing a function only provides behavior; the receiving API decides when to invoke it.

C++

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <numeric>
#include <optional>
#include <functional>
#include <sstream>
#include <variant>
#include <memory>
#include <cctype>
#include <stdexcept>


int main() {
std::cout << std::boolalpha;
int state=0;auto next=[&state](){return ++state;};int first=next();int second=next();std::cout << first+second << "\n";
}

JavaScript

function counter() { let n=0; return () => ++n; }
const c = counter();
console.log(c()+c());

Porting trap: Pass a function value for later use rather than calling it immediately.

The task uses the same rule on new inputs. Return a value from the supplied solve function; leave the input and output plumbing in driver.js.

challenge icon

Challenge

Easy

Input is a nonnegative integer at most 20. Create a counter closure beginning at zero and call it input times. Return its produced sequence beginning with 1.

Input is one JSON value. Edit the unlocked files, starting with exercise.js. The visible locked driver.js calls solve(input) and prints its return value as compact JSON followed by one newline. Do not add diagnostic output. Tests compare the full output. All number inputs and computed integer totals stay within the safe integer range.

Example input:

3

Expected output:

[1,2,3]

Try it yourself

import { readFileSync } from "node:fs";
import { solve } from "./exercise.js";
// One JSON value arrives on stdin. Return data; do not print inside solve.
const input = JSON.parse(readFileSync(0,"utf8"));
console.log(JSON.stringify(solve(input)));
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in JavaScript for C++ Developers

Practice on your own: Online JavaScript compiler