So, I just started learning Javascript, and one of the problems I did was calculating a tip based on a amount paid. This was my first attempt:
var john = {
bills: [124, 48, 268, 180, 42],
calculateTip: function() {
for (var i = 0; i < this.bills.length; i++) {
if (this.bills[i] < 50) {
this.tips[i] = this.bills[i] * 0.2;
} else if (this.bills[i] < 200) {
this.tips[i] = this.bills[i] * 0.15;
} else {
this.tips[i] = this.bills[i] * 0.1;
}
}
return this.tips;
}
};
john.calculateTip();
console.log(john.tips);
But this was the error I would get:
Uncaught TypeError: Cannot set property '0' of undefined
at Object.calculateTip (script.js:8)
at script.js:17
calculateTip @ script.js:8
(anonymous) @ script.js:17
Then I just declared a empty array inside of a object:
var john = {
bills: [124, 48, 268, 180, 42],
tips: [],
calculateTip: function() {
for (var i = 0; i < this.bills.length; i++) {
if (this.bills[i] < 50) {
this.tips[i] = this.bills[i] * 0.2;
} else if (this.bills[i] < 200) {
this.tips[i] = this.bills[i] * 0.15;
} else {
this.tips[i] = this.bills[i] * 0.1;
}
}
return this.tips;
}
};
john.calculateTip();
console.log(john.tips);
And it worked just fine.
My question is
When I was making a normal variable inside a function inside of a object, and not an array, I didn't have to declare it beforehand. Is this always the case with arrays, and if someone can explain the error I got a bit more?