6

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
11
  • 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 need let (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 Commented Dec 30, 2021 at 10:51
  • @NickParsons can u please update in comment . Commented Dec 30, 2021 at 10:52
  • Sorry, not quite sure what you mean by "update in comment"? 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 why totalRecords is undefined when you log it. Move console.log('::'+ totalRecords); and any other code that relies on rows inside of your callback function. 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 Commented Dec 30, 2021 at 11:12

2 Answers 2

7

In 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'

Sign up to request clarification or add additional context in comments.

Comments

4

Make it let instead of constas you are re-assigning the totalRecords variable

2 Comments

but getting undefined value
After I changed to let it's giving this error "Missing semicolon". I swear semicolon is there as mentioned below. let expectedApp: AutomatedApplication = {};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.