Javascript const syntax error

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 pract...

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

Oleg's user avatar

Oleg

9,2712 gold badges44 silver badges58 bronze badges

asked Mar 24, 2014 at 7:12

Vivek P's user avatar

7

The const and let are part of ECMAScript 2015 (a.k.a. ES6 and Harmony), and was not enabled by default in Node.js 0.10 or 0.12. Since Node.js 4.x, “All shipping [ES2015] features, which V8 considers stable, are turned on by default on Node.js and do NOT require any kind of runtime flag.”. Node.js docs has an overview of what ES2015 features are enabled by default, and which who require a runtime flag. So by upgrading to Node.js 4.x or newer the error should disappear.

To enable some of the ECMAScript 2015 features (including const and let) in Node.js 0.10 and 0.12; start your node program with a harmony flag, otherwise you will get a syntax error. For example:

node --harmony app.js

It all depends on which side your strict js is located. I would recommend using strict mode with const declarations on your server side and start the server with the harmony flag. For the client side, you should use Babel or similar tool to convert ES2015 to ES5, since not all client browsers support the const declarations.

gregers's user avatar

gregers

12.2k8 gold badges45 silver badges41 bronze badges

answered Apr 18, 2014 at 9:16

Alexander's user avatar

AlexanderAlexander

3,8951 gold badge11 silver badges16 bronze badges

4

If this is happening in nodejs, it is due to the older version of nodejs. Update node by using,

1) Clear NPM’s cache:

sudo npm cache clean -f

2) Install a little helper called ‘n’

sudo npm install -g n

3) Install latest stable NodeJS version

sudo n stable

Update nodejs instructions taken from, https://stackoverflow.com/a/19584407/698072

Community's user avatar

answered Feb 5, 2016 at 7:31

Stranger's user avatar

StrangerStranger

10.1k18 gold badges77 silver badges112 bronze badges

6

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

answered May 24, 2017 at 21:37

G G's user avatar

G GG G

1,6041 gold badge12 silver badges11 bronze badges

1

One important step after you update your node is to link your node binary to the latest installed node version

sudo ln -sf /usr/local/n/versions/node/6.0.0/bin/node /usr/bin/node  

answered Dec 10, 2016 at 6:16

Shri Shinde's user avatar

Shri ShindeShri Shinde

3092 silver badges6 bronze badges

4

This is probably not the solution for everyone, but it was for me.

If you are using NVM, you might not have enabled the right version of node for the code you are running. After you reboot, your default version of node changes back to the system default.

Was running into this when working with react-native which had been working fine. Just use nvm to use the right version of node to solve this problem.

answered Mar 19, 2016 at 18:30

boatcoder's user avatar

boatcoderboatcoder

17.1k18 gold badges112 silver badges177 bronze badges

3

Since the time the question was asked, the draft for the const keyword is already a living standard as part of ECMAScript 2015. Also the current version of Node.js supports const declarations without the --harmony flag.

With the above said you can now run node app.js, with app.js:

'use strict';
const MB = 1024 * 1024;
...

getting both the syntax sugar and the benefits of strict mode.

answered Oct 7, 2015 at 19:34

dodev's user avatar

dodevdodev

1511 silver badge8 bronze badges

1

I had a similar issue recently and ended up in this Q&A. This is not the solution the OP was looking for but may help others with a similar issue.

I’m using PM2 to run a project and in a given staging server I had a really old version of Node, NPM and PM2. I updated everything, however, I kept keeping the same error:

SyntaxError: Use of const in strict mode.

I tried to stop and start the application several times. Also tried to update everything again. Nothing worked. Until I noticed a warning when I ran pm2 start:

>>>> In-memory PM2 is out-of-date, do:
>>>> $ pm2 update
In memory PM2 version: 0.15.10
Local PM2 version: 3.2.9

Gotcha! After running pm2 update, I finally was able to get the application running as expected. No «const in strict mode» errors anymore.

answered Feb 13, 2019 at 20:36

Gustavo Straube's user avatar

Gustavo StraubeGustavo Straube

3,7096 gold badges39 silver badges62 bronze badges

I was using pm2 to start and maintain the node processes.

From the CLI it worked perfectly.

which node
/usr/local/bin/node
node -v
v10.15.0

However, I set up a cronjob and I got the syntax error.

Then wrote a cronjob to check which node and node -v and surprisingly, it was a different path and version.

which node
/usr/bin/node
node -v
v0.10.48

To fix the cronjob I had to use the flag --interpreter for pm2, like so:

pm2 start dist/server.js --interpreter=/usr/local/bin/node 

answered May 4, 2021 at 15:39

Klaassiek's user avatar

KlaassiekKlaassiek

2,4231 gold badge22 silver badges38 bronze badges

The use of const in strict mode is available with the release of Chrome 41.
Currently, Chrome 41 Beta is already released and supports it.

answered Feb 26, 2015 at 22:01

morkro's user avatar

morkromorkro

4,1065 gold badges25 silver badges35 bronze badges

1

cd /
npm install -g nave
nave use 6.11.1
node app.js

answered Jul 13, 2017 at 22:08

Ayhmi's user avatar

5

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.

Community's user avatar

answered Mar 24, 2014 at 7:27

Shital Shah's user avatar

Shital ShahShital Shah

60.4k15 gold badges230 silver badges181 bronze badges

3

SyntaxError:пропущено=в const-декларации

Исключение JavaScript «отсутствует = в объявлении константы» возникает, когда объявлению const RED_FLAG; не было присвоено значение в том же операторе (например, const RED_FLAG; ). Вам необходимо предоставить один ( const RED_FLAG = '#ff0' ).

Message

SyntaxError: Missing initializer in const declaration (V8-based)
SyntaxError: missing = in const declaration (Firefox)
SyntaxError: Unexpected token ';'. const declared variable 'x' must have an initializer. (Safari)

Error type

Что пошло не так?

Константа — это значение, которое программа не может изменить во время нормального выполнения. Он не может быть изменен путем переназначения и не может быть повторно объявлен. В JavaScript константы объявляются с помощью ключевого слова const . Требуется инициализатор для константы; то есть вы должны указать его значение в том же заявлении, в котором оно объявлено (что имеет смысл, учитывая, что его нельзя будет изменить позже).

Examples

Пропавший инициализатор

В отличие от var или let , вы должны указать значение для объявления const . Это бросает:

Исправление ошибки

Существует несколько вариантов исправления этой ошибки.Проверьте,что должно было быть достигнуто с помощью рассматриваемой константы.

Добавление постоянной величины

Укажите постоянное значение в том же заявлении,в котором оно было объявлено:

const , let или var ?

Не используйте const , если вы не собирались объявлять константу. Возможно, вы хотели объявить переменную с блочной областью видимости с помощью let или глобальную переменную с помощью var . Оба не требуют начального значения.

See also

  • const
  • let
  • var


JavaScript

  • СинтаксисОшибка:отсутствует}после списка свойств

    Исключение JavaScript «отсутствует после списка свойств» возникает, когда где-то есть ошибка в синтаксисе инициализатора объекта.

  • SyntaxError:пропущенный формальный параметр

    Исключение JavaScript «отсутствует формальный параметр» возникает, когда ваши параметры объявления функции действительны.

  • SyntaxError:отсутствующее имя после оператора .

    Исключение JavaScript «отсутствует имя после оператора точки, используемого для доступа к свойству.

  • SyntaxError:missing)после списка аргументов

    Исключение JavaScript «отсутствует после списка аргументов» возникает, когда возникает ошибка при вызове функции.

ES6 introduced the const keyword, which is used to define a new variable in JavaScript. Generally, the var keyword is used to declare a JavaScript variable. Const is another keyword to declare a variable when you do not want to change the value of that variable for the whole program.

The difference is just that var is for normal variable declaration whose value can be changed, whereas a variable value declared using const keyword cannot be changed.

Const variable declaration/initialization

Following is the syntax or simple code for const variable declaration and initialization.

Copy Code

Test it Now

Output

It will display the value of the const variable x without any error.

The value of const variable x = 16

Now, we will discuss some properties of the variables defined using const.

Properties

Following are the properties of const variable:

  1. Variable define using const keyword cannot be reassigned, or its value cannot be changed.
  2. The const variable must be initialized at the time of declaration with the variable name, e.g., const x=6;
  3. You cannot provide the value to the variable after declaration.
  4. The value of the const variable cannot be changed.
  5. The const variable has block scope. This means that a const variable within the same program can be reassigned by the same name and have different values in different blocks.
  6. A const variable cannot be hoisted, which means that a variable declared/initialized using var keyword cannot be reassigned using const.
  7. In JavaScript, const allows you to only modify the value of the array, but the reference to the array cannot be changed.
  8. The const variable creates only reference to the value.
  9. Object properties can be changed but the reference to an object cannot be changed.

Examples

Here, we have some examples for different properties explanation practically.

Example 1: With the help of this example, you will see that the const variable cannot be reassigned.

Copy Code

Test it Now

Output

It will generate a type error because it is not possible to reassign the value to a constant variable.

JavaScript error: Uncaught TypeError: Assignment to constant variable. on line 3

Example 2: In this example, you will learn that the const variable contains Block scope.

Copy Code

Test it Now

Output

There will be no error by executing the above code. It will just print the value of x of different blocks without any syntax or type error.

Block2: x = 23
Block3: x = 74
Block4: x = 49
Block1: x = 16

Example 3: This example will describe that the const variable cannot be hoisted.

Copy Code

Test it Now

Output

It will generate a syntax error because redeclaration of a variable is not allowed.

JavaScript error: Uncaught SyntaxError: Missing initializer in const declaration on line 4

Example 4: This example will show you that the const variable cannot be initialized after declaration.

Copy Code

Output

It will generate a syntax error because initialization is not allowed after the declaration of const variable.

JavaScript error: Uncaught SyntaxError: Missing initializer in const declaration on line 2

Example 5: In JavaScript, const allows you to only modify the value of the array, but the reference to the array cannot be changed.

Copy Code

Output

Here, you can see the Manya name has been replaced by Krishna. Although the array was declared using const keyword. So, it will display all values of the array without any error both times.

Aparna, Manya, Amayra, Jahanvi
Aparna, Krishna, Amayra, Jahanvi

Example 6: In this example, we will show you that the const variable value cannot be changed or modified.

Copy Code

Output

Here, you can see that you cannot reinitialize the object values by the same name, but the object values can be changed by using their reference.

[object object] [object object] 

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Java обработка error
  • Heater error код ошибки на скания r440
  • Java как исправить ошибку 1632
  • Hearts of iron 4 ошибка при установке
  • Janome ошибка bl

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии