SyntaxError: Use of const in strict mode

2019-01-01 03:05发布

I'm working with node.js, and in one of my js files I'm using const in "strict mode". When trying to run it, I'm getting an error:

SyntaxError: Use of const in strict mode.

What is the best practice to do this?

Edit:

'use strict'
const MAX_IMAGE_SIZE = 1024*1024; // 1 MB

9条回答
长期被迫恋爱
2楼-- · 2019-01-01 03:57

Usually this error occurs when the version of node against which the code is being executed is older than expected. (i.e. 0.12 or older).

if you are using nvm than please ensure that you have the right version of node being used. You can check the compatibility on node.green for const under strict mode

I found a similar issue on another post and posted my answer there in detail

查看更多
查无此人
3楼-- · 2019-01-01 04:05
cd /
npm install -g nave
nave use 6.11.1
node app.js
查看更多
有味是清欢
4楼-- · 2019-01-01 04:08

const is not supported by ECMAScript. So after you specify strict mode, you get syntax error. You need to use var instead of const if you want your code to be compatible with all browsers. I know, not the ideal solution, but it is what it is. There are ways to create read-only properties in JavaScript (see Can Read-Only Properties be Implemented in Pure JavaScript?) but I think it might be overkill depending on your scenario.

Below is browser compatibility note from MDN:

Browser compatibility

The current implementation of const is a Mozilla-specific extension and is not part of ECMAScript 5. It is supported in Firefox & Chrome (V8). As of Safari 5.1.7 and Opera 12.00, if you define a variable with const in these browsers, you can still change its value later. It is not supported in Internet Explorer 6-10, but is included in Internet Explorer 11. The const keyword currently declares the constant in the function scope (like variables declared with var).

Firefox, at least since version 13, throws a TypeError if you redeclare a constant. None of the major browsers produce any notices or errors if you assign another value to a constant. The return value of such an operation is that of the new value assigned, but the reassignment is unsuccessful only in Firefox and Chrome (at least since version 20).

const is going to be defined by ECMAScript 6, but with different semantics. Similar to variables declared with the let statement, constants declared with const will be block-scoped.

查看更多
登录 后发表回答