The examples in this book are all presented in C++. That’s the language I do most of my programming in, and it’s the language I’m most proficient in.

If you’re a JavaScript programmer, don’t despair—the Rules are still useful! You don’t need to learn how to program in C++ in order to read the examples in this book. Code is code, basically—a loop is a loop, variables are variables, and functions are functions. There are some cosmetic differences, but the basic ideas in this book’s C++ examples translate pretty directly to JavaScript, even when that translation isn’t immediately obvious!

This appendix explains how to do that translation—how to read C++ and convert it in your head to the JavaScript equivalent. You won’t be able to write C++ code after working your way through this appendix—that would take a whole book—but you should be much more capable of reading it.

Types

Time for an example! Here’s a simple function that calculates the sum of an array of numbers, first in JavaScript: 1

function calculateSum(numbers) {

    let sum = 0;

    for (let number of numbers)
        sum += value

    return sum;
}

And then in C++:

int calculateSum(const vector<int> & numbers)
{
    int sum = 0;

    for (int number : numbers)
        sum += number;

    return sum;
}

Um…it’s the same code. Maybe we don’t need an appendix after all.

Or maybe we do. JavaScript syntax was heavily influenced by C syntax, and I won’t have to explain what curly braces and semicolons mean like I did in the Python appendix, but there are plenty of quirky differences.

First, everything in C++ is scoped. Imagine a let or const before every variable defined in the examples, because that’s implicitly true for all variables in C++.

If you haven’t dabbled in TypeScript yet—if you’ve stuck to straight JavaScript so far in your programming career—then the explicit types in the example might be confusing. The int and const vector<int>& type annotations tell the C++ compiler what kinds of values to expect—in this case, an integer and a list of integers. The compiler needs to know the types before it can actually compile the code.

There are types in JavaScript, too, of course, even if the language doesn’t force you to worry about them. If you do care about the type of an expression, you can call typeof() , but typically you don’t care. In JavaScript the type details are usually sorted out when the code runs, not when it’s compiled. Not always, though—your web browser tries pretty hard to infer types for everything, because if it can then the JavaScript can be compiled to a more efficient form and run a lot faster.

C++ skips right to the “run a lot faster” part, even if that adds some extra steps to writing code. Knowing about types also lets the compiler detect a whole class of bugs earlier, which is a huge advantage.

Here’s how you can tell that both of these approaches are appealing: new versions of C++ let you skip the type annotations in lots of cases, and the increasingly popular TypeScript extension of JavaScript lets you type annotations. Now you can write JavaScript/TypeScript that looks more like C++:

function calculateSum(numbers: int[]): int {

    let sum: int = 0;

    for (let number of numbers)
        sum += number;

    return sum;
}

And C++ that looks more like JavaScript:

auto calculateSum(const vector<int> & numbers)
{
    auto sum = 0;

    for (auto number : numbers)
        sum += number;

    return sum;
}

The examples in this book stick to “old-school” C++ and use explicit types. That’s our policy at Sucker Punch—we think it makes the code easier to read—so I’ve continued the practice here .

Arrays

Despite the surface similarity between C++ and JavaScript, there’s an endless list of quirky differences. Here’s a simple example that reverses the values in an array, first in JavaScript:

function reverseList(values) {

    let reversedValues = []

    for (let index = values.length; --index >= 0; ) {
        reversedValues.push(values[index]);
    }

    return reversedValues;
}

And then in C++:

vector<int> reverseList(const vector<int> values)
{
    vector<int> reversedValues;

    for (int index = values.size(); --index >= 0; )
        reversedValues.push_back(values[index]);

    return reversedValues;
}

Again, the code looks very similar. The closest analog to a JavaScript array in C++ is the vector type. The concepts are the same, but the details are different. In JavaScript, the length property tells you how many elements are in the array. C++ doesn’t have properties, just data members and methods; you get the count of elements in the vector by calling a size() method.

Similarly, both JavaScript arrays and C++ vectors allow new elements to be appended. In C++, it’s the push_back() method, whereas in JavaScript it’s push() . That’s a pretty easy translation.

It’s worth noting that there are big differences lurking beneath the shared syntax. For instance, the JavaScript array values could be a list array of anything — maybe even a jumble of entirely different types, like [1, “hello”, true]. The C++ vector is always a list of integers, no more and no less.

But that won’t be a problem when you read the C++ examples. JavaScript allows more type flexibility than the C++ examples use, but JavaScript is completely happy to deal with simply typed lists.

Classes

Both C++ and JavaScript support classes, and the syntax for doing so isn’t all that different. The ways the two languages actually implement classes are very different, but that’s not important for the examples in this book. If you think of a C++ class as being like a JavaScript class where all the fields are defined with public or private field declarations, you’ll find the examples easy to follow.

Here’s a JavaScript class implementing a 3D vector concept:

class Vector {

    constructor () {
        ++Vector.#vectorCount;
    }

    set (x, y, z) {
        this.#x = x;
        this.#y = y;
        this.#z = z;
        this.#calculateLength();
    }

    getLength () {
        return this.#length;
    }

    static getVectorCount() {
        return Vector.#vectorCount;
    }

    #calculateLength () {
        this.#length = Math.sqrt(
                                this.#x ** 2 + 
                                this.#y ** 2 + 
                                this.#z ** 2);
    }

    #x = 0
    #y = 0
    #z = 0
    #length = 0
    
    static #vectorCount = 0
};

And here is an equivalent C++ class:

class Vector
{
public:

    Vector() :
        m_x(0.0f),
        m_y(0.0f),
        m_z(0.0f),
        m_length(0.0f)
        { ++s_vectorCount; }
    ~Vector()
        { --s_vectorCount; }

    void set(float x, float y, float z);

    float getLength() const
    {
        return m_length;
    }

    static int getVectorCount()
    {
        return s_vectorCount;
    }

protected:

    void calculateLength();

    float m_x;
    float m_y;
    float m_z;
    float m_length;

    static int s_vectorCount;
};

void Vector::set(float x, float y, float z)
{
    m_x = x;
    m_y = y;
    m_z = z;
    calculateLength();
}

void Vector::calculateLength()
{
    m_length = sqrtf(m_x * m_x + m_y * m_y + m_z * m_z);
}

The two versions of the Vector class have the same pieces, but those pieces are rearranged. The translations are straightforward, for the most part. In JavaScript you need to be explicit with your access to fields with the this keyword, or the class name for class fields:

class Vector {

    getLength () {
        return this.#length;
    }

    static getVectorCount() {
        return Vector.#vectorCount;
    }

    #length = 0
    
    static #vectorCount = 0
};

C++ allows explicit specification in these cases—you’re allowed to specify this-> and Vector:: to disambiguate normal and static member references, respectively—but it also allows implicit use of members, and that’s what the examples all use:

class Vector
{
public:

    float getLength() const
    {
        return m_length;
    }

    static int getVectorCount()
    {
        return s_vectorCount;
    }

protected:

    float m_length;

    static int s_vectorCount;
};

These two examples also show how member visibility is handled in both languages. Private fields have names with a hashtag ( # ) prefix in JavaScript. In C++ the private keyword is used for this—it marks the start of a section where all methods and members being declared are considered private. All of the examples in this book use the similar keyword protected .

Moving on to constructors! In JavaScript, a special constructor function is called when a new Vector is created:

class Vector {

    constructor () {
        ++Vector.#vectorCount;
    }
};

In C++, the class name itself is used for this method. It is nevertheless (and somewhat confusingly) called the constructor :

class Vector
{
public:

    Vector() :
        m_x(0.0f),
        m_y(0.0f),
        m_z(0.0f),
        m_length(0.0f)
        { ++s_vectorCount; }
};

C++ classes also have an important concept that doesn’t really exist in JavaScript—the destructor . An object’s constructor is called when an object is created, and the destructor when it is destroyed. The destructor also uses the class name, this time with a tilde ( ~ ) prepended:

class Vector
{
public:

    ~Vector()
        { --s_vectorCount; }
};

There’s no real equivalent to this in JavaScript—the closest you can come to this is registering a callback with a FinalizationRegistry object, which is a recent and (arguably) underbaked addition to JavaScript. This mechanism doesn’t have quite the same behavior as a C++ destructor. In C++, the destructor is called immediately when an object goes out of scope. Here’s an example where a Vector is created as a local variable inside a function:

void functionA()
{
    printf("%d, \n", Vector::getVectorCount());
    Vector a;
    printf("%d, \n", Vector::getVectorCount());
};

Vector b;
functionA();
printf("%d\n", Vector::getVectorCount());

This code prints “1, 2, 1” when run—the destructor for a is called when functionA returns, so s_vectorCount is decremented immediately. In JavaScript, any finalization callback is triggered by garbage collection, and the timing of garbage collection is implementation-specific. There isn’t a reliable way to get the same timing in JavaScript, as in the preceding C++ example.

That’s too bad. The lack of a destructor rules out some useful tricks—Sucker Punch code often uses object lifetimes as a robust way to manage things, and you’ll see some of this in the C++ examples. Just remember that the destructor gets called immediately and you’ll be able to follow along .

Declarations and Definitions

Next , let’s look at splitting a function’s declaration from its definition. In JavaScript, all of a class’s methods are defined in the class itself:

class Vector {

    set (x, y, z) {
        this.#x = x;
        this.#y = y;
        this.#z = z;
        this.#calculateLength();
    }

    getLength () {
        return this.#length;
    }

Many of the examples in this book will do the same thing in C++:

class Vector
{
public:

    float getLength() const
    {
        return m_length;
    }
};

In other cases, though, the examples will split the declaration of the method. First the code establishes that a method with a given name and type signature exists:

class Vector
{
public:

    void set(float x, float y, float z);
};

The function is then defined separately:

void Vector::set(float x, float y, float z)
{
    m_x = x;
    m_y = y;
    m_z = z;
    calculateLength();
}

These two forms are typically compiled differently in C++, with methods defined inside the class compiled inline , meaning that a separate copy of the function is generated and inserted wherever it’s called, while a single copy exists for functions with a separate definition. That’s not important for the examples in this book, though, so don’t worry about the distinction .

Function Overloading

There are other features in C++ that don’t have direct analogs in JavaScript. The converse is true, as well, of course—there are lots of JavaScript features that C++ doesn’t have—but that’s unimportant here, since we’re focused on reading C++ code.

One thing that can be confusing to JavaScript programmers is seeing two functions with the same name. Here’s an example in C++:

int min(int a, int b)
{
    return (a <= b) ? a : b;
}

int min(int a, int b, int c)
{
    return min(a, min(b, c));
}

void example()
{
    printf("%d %d\n", min(5, 8), min(13, 21, 34));
}

It’s not clear how this works—if you try to call the min function, which version is called? The C++ compiler makes this decision based on the arguments. If two integers are passed, it calls the first one; if three integers, it calls the second one. The example function prints 5 and 13 .

In JavaScript, you’d instead write a single min function that supports an arbitrary number of arguments. Something like this:

function min () {

    if (arguments.length == 0)
        return Infinity;

    let result = arguments[0];
    for (let index = 1; index < arguments.length; ++index) {
        result = Math.min(result, arguments[index])
    }

    return result;
}

This is exactly what Math.min does, of course, so no need to write this function yourself !

Templates

Another concept from C++ that has no Python analog is templates . To simplify things a bit: C++ templates are a way to write one chunk of code that handles multiple types. The compiler generates new code for each set of types used with the template.

The first example in this appendix summed an array of integer values. If you wanted to sum an array of floating-point values, you might write new code:

float calculateSum(const vector<float> & numbers)
{
    float sum = 0;

    for (float number : numbers)
        sum += number;

    return sum;
}

Or you might write a single version of calculateSum using templates and let the compiler do the work for you:

template <class T>
T calculateSum(const vector<T> & numbers)
{
    T sum = T(0);

    for (T number : numbers)
        sum += number;

    return sum;
}

The templated version of calculateSum will work for any type that implements the += operator and supports 0 as a value. That’s true for integers and floating-point values, but could also easily be arranged for other types. You could implement += and 0 for the Vector class from the last section, for instance, and gain the ability to sum an array of Vector s.

In JavaScript, there’s no need for any of this. The JavaScript code I wrote to sum a list of values works perfectly well for any type that supports addition and initialization to 0:

function calculateSum(number) {

    let sum = 0;

    for (let number of numbers)
        sum += number

    return sum;
}

When you see the C++ template syntax in the examples, it usually marks some bit of code that would work fine in JavaScript without any templating at all .

Pointers and References

There’s one final thing that JavaScript mostly hides from view but that C++ makes programmers worry about, and that’s passing arguments by value versus passing them by reference . In JavaScript, simple types like numbers or strings are passed by value—a new copy is made whenever they’re assigned to a variable or passed as an argument to a function. It’s more complicated for types like lists or objects. Here’s an example:

function makeChanges (number, numbers) {
    number = 3;
    numbers.push(21);
    console.log(number, numbers);
}

let number = 0;
let numbers = [3, 5, 8, 13];

console.log(number, numbers);
makeChanges(number, numbers);
console.log(number, numbers);

When this code is run it prints out:

0 (4) [3, 5, 8, 13]
3 (5) [3, 5, 8, 13, 21]
0 (5) [3, 5, 8, 13, 21]

Notice how the simple value changes inside makeChanges to 3, then changes back to 0 when makeChanges returns, but the list changes without changing back. That’s because 0 was passed by value. A new copy was made when makeChanges was called. When makeChanges sets number to 3, it’s only changing the copy.

JavaScript didn’t make a copy of the globalNumbers list—it just passed the original list. Both numbers and globalNumbers are holding onto the same list. When 21 is appended, it’s appended to that list. When numbers is logged before returning or globalNumbers after, 21 shows up, because you’re printing the same list in both cases.

C++, by contrast, makes all of this more explicit. All variables and arguments are explicitly passed by value or passed by reference. The C++ equivalent to the preceding JavaScript code looks like this:

void makeChanges(int number, vector<int> & numbers)
{
    number = 3;
    numbers.push_back(21);
    cout << number << " " << numbers << "\n";
}

The ampersand in front of numbers is important—it tells the compiler that this argument is passed by reference, not by value, so the compiler won’t make a copy of it when makeChanges is called. There’s no ampersand for number , so the compiler does make a copy of number .

If the ampersands are flipped, then the compiler makes a copy of numbers but not of number :

void makeChanges(int & number, vector<int> numbers)
{
    number = 3;
    numbers.push_back(21);
    cout << number << " " << numbers << "\n";
}

This version produces different output. Now it’s the simple value that is permanently changed, while the list pops back to its original value:

0 [3 5 8 13]
3 [3 5 8 13 21]
3 [3 5 8 13]

The examples in this book will often use references to avoid making expensive copies of bulky values. In most cases, the references will be marked with the const keyword to mark something that shouldn’t be altered, despite being passed by reference. That showed up (and was never explained) in the first C++ example in this appendix:

int calculateSum(const vector<int> & numbers);

With this usage, no copy is made of numbers , but the compiler won’t allow any changes to numbers either. In practice this is really similar to passing it by value, but at much lower cost.

As a final note, in a few cases the examples use the other (sigh) C++ syntax for passing things by reference— pointers . Pointers and references are almost exactly the same thing, and the differences aren’t really important if you’re just trying to figure out what the code is doing. The key syntactic differences are:

  • Pointers are defined with * instead of & .

  • Pointers use -> instead of . to get at members.

  • To convert a pointer to a reference, you use * ; to convert a reference to a pointer, you use & .

Here’s the example code written with pointers :

void example(int number, vector<int> * numbers)
{
    number = 3;
    numbers->push_back(21);
    cout << number << " " << *numbers << "\n";
}

void callExample()
{
    int number = 0;
    vector<int> numbers = { 3, 5, 8, 13 };
    cout << number << " " << numbers << "\n";
    example(3, &numbers);
    cout << number << " " << numbers << "\n";
}

This book’s examples use constant references whenever an argument is conceptually being passed by value, but actually passing the argument by value would be expensive. In all other cases, pointers are used.

1 I had to choose a JavaScript version for these examples. For better or worse, I chose ES6. If you’re stuck on a version earlier than that, my apologies.