I am writing mysql query and kept those records in variable, My requirement is to get access that variable in anywhere so declared it outside of route,but it is showing error like : SyntaxError: Missing initializer in const declaration
const totalQuery = "select name from users";
const totalRecords;
dbConn.query(totalQuery,function(err,rows) {
totalRecords = rows.length
})
console.log('::'+ totalRecords);
process.exit();
Error:
SyntaxError: Missing initializer in const declaration
I am writing mysql query and kept those records in variable, My requirement is to get access that variable in anywhere so declared it outside of route,but it is showing error like : SyntaxError: Missing initializer in const declaration
const totalQuery = "select name from users";
const totalRecords;
dbConn.query(totalQuery,function(err,rows) {
totalRecords = rows.length
})
console.log('::'+ totalRecords);
process.exit();
Error:
SyntaxError: Missing initializer in const declaration
Share
Improve this question
asked Dec 30, 2021 at 10:46
user_1234user_1234
7611 gold badge12 silver badges23 bronze badges
10
-
1
When you create the constant you need to initialize it using
=
. You can't declare it and then assign a value to it at a later point, for that you would needlet
(see this MDN article). Note that it also looks like your code will face the following issue: Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference – Nick Parsons Commented Dec 30, 2021 at 10:51 - @NickParsons can u please update in ment . – user_1234 Commented Dec 30, 2021 at 10:52
- Sorry, not quite sure what you mean by "update in ment"? – Nick Parsons Commented Dec 30, 2021 at 10:53
-
1
console.log('::'+ totalRecords);
runs before the code in your callback function:totalRecords = rows.length
. So that is whytotalRecords
isundefined
when you log it. Moveconsole.log('::'+ totalRecords);
and any other code that relies onrows
inside of your callback function. – Nick Parsons Commented Dec 30, 2021 at 11:04 - 1 Please also read: How to return the response from an asynchronous call it looks like a big read, but 100% required knowledge if you want to write a javascript program that deals with asynchronous code (which is what you're trying to do). There is no clear-cut answer to your problem as more context would be needed to get a better idea for what the best option is. I suggest you have a read of the links I've sent to try and get a better idea, you may be able to use Promises here to help, which is also explained the link – Nick Parsons Commented Dec 30, 2021 at 11:12
2 Answers
Reset to default 6In javascript, you can't assign value to 'const' later after it's declaration. You're bound to assign the value to const on the declaration line.
If you really need to declare the value some where later, then better go with 'let'
Make it let
instead of const
as you are re-assigning the totalRecords
variable