mortiped
mortiped

Reputation: 867

don't re-assign variable reloading script

I have a script in JavaScript which is called several times in a html page. I want to know how it's possible to assign values ​​to a variable only the first call of the script.

var processingYear = 0;
var recupMonth = 0;
var recupYear = 0;


if(processingMonth == startMonth && processingYear == startYear && recupMonth == 0 && recupYear == 0){
            recupMonth = startMonth;
            recupYear = startYear;
        }

Upvotes: 4

Views: 80

Answers (3)

sakthi
sakthi

Reputation: 929

window.count ? count="defined" : count="undefined";
if(count=="undefined"){
  var processingYear = 0;
  var recupMonth = 0;
  var recupYear = 0;
}

Just another way to do !

Upvotes: 0

Szymon Drosdzol
Szymon Drosdzol

Reputation: 468

var processingYear = processingYear || 0;

Upvotes: 3

Tibos
Tibos

Reputation: 27833

If i understand correctly you want to include the same script multiple times in the same HTML page. To prevent the script from overwriting your initializations, you can simply check if the variables have values before redefining them:

Instead of:

var x = 2;

Do:

var x = (x !== undefined) ? x : 2;

A shorter version would be var x = x || 2;, but that can backfire if your x variable holds a value that is evaluated to false (for example 0) after the script is executed.

Upvotes: 3

Related Questions