Explain Codes LogoExplain Codes Logo

Syntaxerror: Use of const in strict mode

javascript
javascript-upgrade
es6-support
babel-transpilation
Nikita BarsukovbyNikita Barsukov·Mar 8, 2025
TLDR

Fixing a SyntaxError: Use of const in strict mode essentially involves updating your environment to support ES6. Here's what you need to do:

  • Upgrade Node.js to a version that natively recognises const.
  • If you can't upgrade, use tools like Babel to transpile ES6 to ES5.
  • In cases where the above options are not feasible, simply replace const with var.

Replacement Example:

// ES6 way: const isTheSkyBlue = 'YesIndeed'; var isTheSkyBlue = 'YesIndeed'; // Good ol' ES5

Choose the approach that best suits your environment and compatibility requirements.

Node.js upgrade for ES6 support

Upgrading Node.js directly addresses the SyntaxError issue related to const. To make your upgrade process smooth, follow these steps:

  • Pick a Node.js version manager that you are comfortable with. nvm and n are both great options.
  • To install the latest stable version, run nvm install stable or n latest.
  • Modify any environment paths to reflect the upgrade.
  • Validate the upgrade using node -v.
  • Reboot your system to ensure the newer version of Node.js is active.

If you encounter an issue while upgrading, clearing the NPM cache using npm cache clear --force, is a good first step.

Best practices for const usage

With a supportive Node.js environment, consider the following practices:

  • const should be used for constants, or values that won't change.
  • let is better used for variables that are block-scoped.

Strict mode ('use strict';) acts as an effective coding standards enforcer and should be used at the beginning of your JavaScript files.

ES6 transpilation using Babel

When it comes to ensuring ES6 compatibility, Babel flies to the rescue. Here's how to get it on your team:

npm install --save-dev @babel/core @babel/cli @babel/preset-env npm install @babel/polyfill

Add a .babelrc file with:

{ "presets": ["@babel/preset-env"] }

Then just transpile your code like so:

npx babel timeMachine.js --out-file timeMachine.transpiled.js

Troubleshooting common pitfalls

When using const:

  • Avoid Redefining constants: It's as naughty in strict mode as stealing cookies.
  • Maintaining awareness about scope: const is block-scoped, like a cat that respects personal space.
  • Familiarize with browser compatibility: Transpilation with Babel ensures compatibility with older browsers that hold the city's WiFi ransom.

If stuck, consider these:

  • Check the Node.js binary path: Double-check if it points to the upgraded version.
  • Consult Node.js documentation: It's like a free backstage pass to all ES6 features.
  • Visit node.green: The Times Square of ES6 support information.