Simon Suh
Simon Suh

Reputation: 10882

Why does NOT adding a '+ ""' after a mathematical operation in javascript make the counting of the new variables length undefined?

I'm counting the number of hours and then subtracting it by 12 if it goes above 12 (so that 1pm doesn't appear as 13pm). Below is part of my javascript code.

else if (hours[0] >= 13) {
    hours[0] = hours[0] - 12 + "";
}

Later in the code, when I'm trying count the length of the array variable 'hours[0]', it appears as unknown if I have this code instead:

else if (hours[0] >= 13) {
    hours[0] = hours[0] - 12;
}

and I don't understand why. Could someone help me out please?

Upvotes: 2

Views: 107

Answers (2)

6502
6502

Reputation: 114461

If you add "" to an expression you're converting the resulto to a string and strings have a .length property. Numbers instead do not have a .length so what you're experiencing is normal...

var x = 42;         // this is a number
var y = x + "";     // y is a string ("42")
var z1 = x.length;  // this is undefined (numbers have no length)
var z2 = y.length;  // this is the lenght of a string (2 in this case)

Upvotes: 2

Jonas Høgh
Jonas Høgh

Reputation: 10874

The subtraction hours[0] - 12 returns a number, no matter if hours[0] contains a number or a string containing a number, e.g. "13". Adding the + "" converts the result of the subtraction to a string. A number has no length in javascript, and therefore invoking the length member of a number will return undefined.

Upvotes: 4

Related Questions