Borislav Hadzhiev
Tue Oct 19 2021·2 min read
Photo by Artem Beliaikin
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;
.
Here's an example of how the error occurs.
// ⛔️ 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.
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.
// ✅ let = can be reassigned let country; country = 'Chile'; // ✅ const = Set value upon declaration const age = 30;
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.
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.
// ✅ 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.