Appendix B. Reading C++ for JavaScript Programmers

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 ...

Get The Rules of Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.