Most programming languages change over the years. The update from Python 2 to Python 3, for example, is a famous example of an insane amount of breaking changes that caused many a Python developer to lose more sleep and hair than they would have liked.
JavaScript has also changed a lot over the years, but the interesting thing about being a language that primarily runs in a web browser is that you don't always control the runtime. If you're running Python (or JS, or anything) on a server, then you can update your code, and at the same time update your runtime, or compiler, or interpreter. With frontend JavaScript, you're at the mercy of whatever mix of out-of-date browsers your users are running.
Enter polyfills and transpilers.
A polyfill is an extra bit of code you include to add functionality that some browsers might not support. For example, maybe Chrome allows you to use the fancy new Array.prototype.flat() method, but Internet Explorer 11 doesn't. You can include a polyfill (just some extra JavaScript code) that adds that method to the Array prototype so that your code works in both browsers.
A transpiler (in the context of adding new JavaScript features) is basically a polyfill on steroids. Instead of just adding a method here or a property there, a transpiler will take your entire JavaScript file and convert it into an older version of JavaScript that is known to work in all browsers. For example, it might take your fancy async and await keywords and convert them into a bunch of Promise objects and .then() calls. Babel is the most popular transpiler for JavaScript.
Let's update our heifer code. Instead of statically saying moo!, the code should say moo, NAME!, where NAME is a variable you define and is dynamically inserted using a template literal.
Template literals (strings wrapped in backticks `) are modern feature of JavaScript. However, older browsers may not support them. We'll use Babel to ensure compatibility.
npm i -D @babel/core @babel/cli @babel/preset-env
@babel/core – the main Babel package. It provides the core functionality for transpiling JavaScript.@babel/cli – a CLI that will let us run Babel.@babel/preset-env – a preset that automatically determines which JavaScript features need to be transpiled.If you haven't done so already, now would be a great time to create a .gitignore file and add node_modules/ to it.
{
"presets": ["@babel/preset-env"]
}
This tells Babel to transpile your code based on what’s needed for older browsers. You can set targets for preset-env. See the docs for more info.
npx babel main.js --out-file main.compiled.js
Run and submit the CLI tests.