Hawkeye
Hawkeye

Reputation: 377

Adding a number to an undefined value

In the JS example:

 var test;

 function test () {
     var t = test + 1;
     alert(t);
 }

I am trying to make a counter but if I set test to 0, it still always gives me 1. I don't know what I am doing wrong. I am activating the function through a button.

Upvotes: 1

Views: 16329

Answers (3)

RobG
RobG

Reputation: 147453

If you aren't in control of test, you might do something like:

// Test if test is a number, if not, convert it
if (typeof test != 'number') {
  test = Number(test);
}

// If conversion resulted in NaN, set to a default
if (isNaN(test) {
  test = 0;
}

// Now it's safe to do addition
test += 1

Of course that is all pretty tedious and can be replaced with:

test = (+test || 0) + 1;

Upvotes: 2

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107566

You should define test as 0 to begin with so that it starts out as an object of type Number. Adding numbers to undefined results in NaN (not-a-number), which won't get you anywhere.

So now to address your issue of why the number never goes past 1, the first mistake is that you actually don't increment the value of test in your code, you just assign the result of temporarily adding 1 to it to t before alert()ing that result. There's no mutation of test here. Use a pre- or post-increment operator or set the result of test + 1 back to test to update it.

Secondly, you should probably not have a function and a local variable named the same, it just confuses things.

Taking all of these into account, we get:

var test = 0; // Now test is a Number

function testIncrementOne() { // name change to prevent clashing/confusing
    var t = ++test;    // pre-increment (adds 1 to test and assigns that result to t)
    // var t = test++; // post-increment (assigns the current value of test to t 
                       // and *then* increments test)
    alert(t);
}

Or just:

 function testIncrementOne() {
    alert(++test);
}

Upvotes: 7

stackErr
stackErr

Reputation: 4170

I think what you want is this:

var test = 0;

 function incrementTest() {
     test = test + 1;
     alert(test);
 }

Upvotes: 2

Related Questions