0

I have a line in my source code written by someone else:

var campaignLimits = 10, campaignsArray = new Array();

I just wanted to know, whether campaignsArray here becomes global variable, or the var applies to campaignsArray as well?

Mohit Bhardwaj
  • 8,005
  • 3
  • 29
  • 60
  • 1
    is it written inside a function ? – Sharath Bangera Nov 30 '16 at 08:28
  • 2
    `var campaignLimits = 10, campaignsArray = new Array();` is the same as `var campaignLimits = 10; var campaignsArray = new Array();`. Whether they're global or not will depend on the scope where they're defined. – phoa Nov 30 '16 at 08:28
  • the second one. for testing you can put it in a function and console.log that variable outside of that function. – marmeladze Nov 30 '16 at 08:29
  • var applies to campaignsArray as well. It's supported by Douglas Crockford, you may find some articles on this choice : http://sixrevisions.com/javascript/single-var-pattern/ and its critic http://danhough.com/blog/single-var-pattern-rant/ – lkostka Nov 30 '16 at 08:29
  • Both `campaignLimits` and `campaignArrays` become a variable within a current scope. If you declare it in a global scope, they will both become global variables. – Yeldar Kurmangaliyev Nov 30 '16 at 08:29
  • @SharathBangera yes, it is inside a function. – Mohit Bhardwaj Nov 30 '16 at 08:29
  • (function() { var campaignLimits = 10, campaignsArray = new Array(); })(); run this in your console, its not global as it is inside a function – Sharath Bangera Nov 30 '16 at 08:29
  • @phoa Yes, I actually just wanted to know if it's equivalent to adding a var before the second variable declaration. You can add it as an answer. – Mohit Bhardwaj Nov 30 '16 at 08:30
  • It behaves exactly as the [documentation](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/var) says it does. In any case, this would be trivial to test in the console. –  Nov 30 '16 at 08:53

1 Answers1

0

Assuming you have not used any programming pattern, If its written inside a function then its not global.

(function() { var campaignLimits = 10, campaignsArray = new Array(); })();

as @phoa commented it is same as

(function() { var campaignLimits = 10; var campaignsArray = new Array(); })();

Try it in your console and see whether you will be able to access campaignsArray.

  • What do you mean by "assuming you have not used any programming pattern"? –  Nov 30 '16 at 08:54