JavaScript Variable declaration and initialization in JavaScript/Node.JS variable declaration initialization assignment,variable declaration initialization,variable declaration initialization

I have seen different recommendation of coding format/styles in JavaScript. One of them is to omit , and ; at the end of each line unless the , is used in a JSON object. Another is to use only var to declare variables and indent 2nd variable onward.

I adopted both recommendation and this has caused me one interesting bug that I'd like to seek deeper understanding of the issue.

Initialization

var max = 2
    arr = []
    wait = 10

//Preset arr with simple object {id:i}
for(var i = 0; i < max; i++) arr.push({id:i})

Main Function

function simulate(idIn, callback) {
    var msg = idIn 
        id = idIn

    logger.info(idIn, 'simulate', JSON.stringify({id:id, idIn:idIn}))
    setTimeout(function() {
        var obj = {id:id, idIn:idIn}
        logger.info(idIn, 'init', JSON.stringify(obj))
        callback()
    }, wait)
}

Paralleled Execution

async.map(arr, function(item, cb) {
    logger.info('map', JSON.stringify(item))
    simulate(item.id, cb)
}, function(err, result) {})

Output

info: map {"id":0}
info: 0 'simulate' '{"id":0,"idIn":0}'
info: map {"id":1}
info: 1 'simulate' '{"id":1,"idIn":1}'
info: 0 'init' '{"id":1,"idIn":0}'  //id is overwritten here 
info: 1 'init' '{"id":1,"idIn":1}'

As you can see from the output, the local variable id is overwritten with incoming value of idIn parameter during the wait. I fixed the issue by simply adding a , in the variable declaration of the simulate function.

    var msg = idIn, //Added comma here. 
        id = idIn

I suppose this means , cannot be omitted in multiple variable declaration if you want to use only one var keyword. I'm trying to understand what happens to the 2nd variable id when , is omitted? Does this change its scope or it's made to something else?

Answer:1

JavaScript, like every programming language, has its syntactical rules.
And I suggest you to study them, before following any kind of recommendation (and the one you have followed is terrible, IMHO).

One of these rules is that ; (which is used to separate statements):

  • is required when you have two (or more) statements on the same line
  • is optional if the statement is followed by a line break

Another rule says that you have to use the var keyword to declare a variable, and its scope depends on where this declaration happens.

  1. When you declare a variable inside a function, e.g.:

    function f() {
        var v;
    }
    

    the variable v will have a local scope, i.e. it can be only accessed within the function f.

  2. Otherwise, when you declare a variable outside a function, e.g.:

    var v;
    

    the variable v will have a global scope, i.e. it can be accessed by every script and function on the same page.

  3. Even if you assign a value to a variable that has not been declared, e.g.:

    function f() {
        v = "hello world";
    }
    

    the variable v will automatically become a global variable.

So, since in your code you have written:

var msg = idIn 
    id = idIn

which means:

var msg = idIn;
id = idIn;

it makes id a global variable.

Answer:2

I'm using mongoose to count the number of documents that match a certain query. My index for this query is: {createdAt: -1, status: -1, oId: -1} Mongo version is 3.2, amount of docs in the collection ...

I'm using mongoose to count the number of documents that match a certain query. My index for this query is: {createdAt: -1, status: -1, oId: -1} Mongo version is 3.2, amount of docs in the collection ...

I've a statically created table: <table id="table" style="width:100%"> <tbody id="tbody"> </tbody> </table> I've dinamically created some elements: var tbody = ...

I've a statically created table: <table id="table" style="width:100%"> <tbody id="tbody"> </tbody> </table> I've dinamically created some elements: var tbody = ...

  1. jquery cdn
  2. jquery ajax
  3. jquery each
  4. jquery on
  5. jquery ui
  6. jquery document ready
  7. jquery find
  8. jquery append
  9. jquery selector
  10. jquery css
  11. jquery on click
  12. jquery add class
  13. jquery post
  14. jquery remove class
  15. jquery download
  16. jquery get
  17. jquery disable button
  18. jquery datepicker
  19. jquery animate
  20. jquery innerhtml

I am trying to load in a external html file and stringify the contents within the body but can't seem to do so without it producing undesired results. Is there even a way to do this? var xhr = new ...

I am trying to load in a external html file and stringify the contents within the body but can't seem to do so without it producing undesired results. Is there even a way to do this? var xhr = new ...

I have this sample: link CODE HTML: <input class="required-input" id="ssn" maxlength="9" type="text" name="ssn" placeholder="123-45-6789"> CODE CSS: .valid{ border:1px solid blue; } ....

I have this sample: link CODE HTML: <input class="required-input" id="ssn" maxlength="9" type="text" name="ssn" placeholder="123-45-6789"> CODE CSS: .valid{ border:1px solid blue; } ....

  1. social security number format
  2. social security number suspended
  3. social security number lookup
  4. social security number meaning
  5. social security number office
  6. social security number stolen
  7. social security number application
  8. social security number by state
  9. social security number verification
  10. social security number florida
  11. social security number generator
  12. social security number validator
  13. social security number phone number
  14. social security number for newborn
  15. social security number replacement
  16. social security number office near me
  17. social security number starting with 8
  18. social security number blocked
  19. social security number near me
  20. social security number protection