Fix - Missing initializer in const declaration Error in JS

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

Fix - Missing initializer in const declaration Error #

The "Missing initializer in const declaration" error occurs when a variable is declared using const, but its value is not initialized on the same line. To solve the error, initialize the variable on the same line you declare it, e.g. const num = 30;.

missing initializer in const declaration

Here's an example of how the error occurs.

index.js
// ⛔️ Missing initializer in const declaration const country; // ⛔️ Missing initializer in const declaration const age; age = 30;

We declared a variable using the const keyword, however we didn't initialize its value, so we got the "Missing initializer in const" error back.

Variables declared using const cannot be reassigned, therefore we have to set their value upon declaration.

If you need to declare a variable, which can be reassigned, you should use the let statement instead.

index.js
// ✅ let = can be reassigned let country; country = 'Chile'; // ✅ const = Set value upon declaration const age = 30;
If you can't figure out where the error occurs, look at the error message in your browser or your Node.js terminal. The error message should display the file in which the error occurred and the specific line.

Variables declared using the let statement can be reassigned at a later point in time in our code. However, note that they cannot be redeclared.

index.js
let country; // ⛔️ Identifier 'country' has already been declared let country = 'Chile';

We tried to redeclare the country variable and got an error. Instead, omit the let keyword when reassigning a variable declared using let.

If you don't need to reassign the variable at a later point in time, you can use the const keyword and set its value when declaring the variable.

index.js
// ✅ Works const country = 'Chile'; // ⛔️ Error: Assignment to constant variable country = 'Brazil';

Variables declared using the const keyword cannot be reassigned, which makes your code easier to read when that is the intent.

It lets the reader of your code know that this variable will not be reassigned at a later point.

Use the search field on my Home Page to filter through my more than 1,000 articles.