So it’s quite common for an engine to implement only the part of the standard.
A good page to see the current state of support for language features is https://kangax.github.io/compat-table/es6/ (it’s big, we have a lot to study yet).
As programmers, we’d like to use most recent features. The more good stuff – the better!
On the other hand, how to make our modern code work on older engines that don’t understand recent features yet?
There are two tools for that:
Here, in this chapter, our purpose is to get the gist of how they work, and their place in web development.
A transpiler is a special piece of software that translates source code to another source code. It can parse (“read and understand”) modern code and rewrite it using older syntax constructs, so that it’ll also work in outdated engines.
??. So, if a visitor uses an outdated browser, it may fail to understand the code like
height = height ?? 100.
A transpiler would analyze our code and rewrite
height ?? 100 into
(height !== undefined && height !== null) ? height : 100.
// before running the transpiler height = height ?? 100; // after running the transpiler height = (height !== undefined && height !== null) ? height : 100;
Usually, a developer runs the transpiler on their own computer, and then deploys the transpiled code to the server.
Speaking of names, Babel is one of the most prominent transpilers out there.
Modern project build systems, such as webpack, provide means to run transpiler automatically on every code change, so it’s very easy to integrate into development process.
New language features may include not only syntax constructs and operators, but also built-in functions.
Math.trunc(n) is a function that “cuts off” the decimal part of a number, e.g
Math.trunc, so such code will fail.
As we’re talking about new functions, not syntax changes, there’s no need to transpile anything here. We just need to declare the missing function.
A script that updates/adds new functions is called “polyfill”. It “fills in” the gap and adds missing implementations.
For this particular case, the polyfill for
Math.trunc is a script that implements it, like this:
Two interesting libraries of polyfills are:
- core js that supports a lot, allows to include only needed features.
- polyfill.io service that provides a script with polyfills, depending on the features and user’s browser.
Just don’t forget to use transpiler (if using modern syntax or operators) and polyfills (to add functions that may be missing). And they’ll ensure that the code works.
Good resources that show the current state of support for various features:
- https://caniuse.com/ – for browser-related functions.
P.S. Google Chrome is usually the most up-to-date with language features, try it if a tutorial demo fails. Most tutorial demos work with any modern browser though.