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?
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.