Skip to main content

Babel

A great way to see how Babel does code transformation (”transpilation”) is to use Babel’s REPL. Try entering the code below in the lefthand pane to see the javascript it produces on the righthand side:

const myObject = {
definitelyAnObject: {},
maybeAnObject: undefined,
};

// example of the "optional chaining" language feature
const maybeValue = myObject.maybeAnObject?.value;

Permalink to REPL with this code & preset config.

The code that’s produced by adding this small ? before we try to read value might seem convoluted but it’s important to see why it’s needed for a language like Javascript. We often need to write defensive code to avoid errors in dealing with dynamic data structures and changing data types at runtime. This small change enables us to avoid writing extra conditional checks before trying to retrieve the value we want. It’s just one of the newer language features that babel enables us to use right away, before browser javascript engines support them.

You can use a tool like caniuse and node.green to see which engine versions support which features natively, to determine whether you need Babel to do specific translations.