Question

This isn't a problem as such - more a general enquiry.

The following (working code) loops through a table of cart items, fetches the price and quantity entered for each item, and adds the results into the variable "cartTotal".

function updateCart(){
    var cartTotal = 0;
    jQ('#cartItems').find('tr').each(function(){
        $this = jQ(this);
        var price = $this.find('.itemPrice').text();
            price = Number(price.replace(/[^0-9\.]+/g,""));
        var qty = $this.find('input').val();
        var itemTotal = ( price * qty );
        cartTotal += itemTotal;
    });
    console.log(cartTotal);
};

Initially, I declared cartTotal without giving it a value of 0 - I assumed that with javascript being loosely typed, it would "know" cartTotal is a number as soon as numbers were added to it, as this is what I'd been lead to understand from various posts/articles I've read. But the console logged NaN.

Perhaps I've taken the "loosely typed" feature a bit too literally. Could somebody shed some light onto why not giving it an initial value yielded NaN?

Was it helpful?

Solution

The reason is that you are trying to add a number to an undefined variable, for JavaScript undefined + 10 for ex returns NaN, you could try it out with the following:

var cartTotal;
cartTotal += 10;
console.log(cartTotal);

For a great explanation on the difference between null and undefined look at this answer: Why is null an object and what's the difference between null and undefined?

Loosely typed means that a variable is declared without its type, so

var answer = 42;

is loosely typed, it's just a generic box holding the Number 42, when it comes to number addition the compiler knows how to sum the two and gives you the result.

OTHER TIPS

var cartTotal is undefined but you then try to use it using +=. This will not work as JavaScript does not know what type cartTotal is as you haven't set it to 0. Its not strong types so has no way of knowing to convert undefined to 0.

See: Example

var cartTotal; // Undefined
var cartTotal = 0; // Defined as number


var cartTotal;
var itemTotal = 12;
alert("Cart total type: " + typeof(cartTotal)); // Causes an ex so returns NaN.
cartTotal += itemTotal; 
alert(cartTotal);

var cartTotal = 0;
var itemTotal = 12;
alert("Cart total type: " + typeof(cartTotal));
cartTotal += itemTotal; 
alert(cartTotal);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top