Reputation: 49
If I have a simple object like this:
const currentAccount = [{
name: 'J.Edge',
balance: 100,
}]
Firstly, am I right in thinking (forgive my newbie-ness, only been learning JS for a few weeks) that I can't add to the numeric balance property directly, like in the function below, because of JS type coercion converting the balance property's 100 to a string?
const withdraw = (amount) => {
currentAccount.balance - amount
return Object.keys(currentAccount)
}
And secondly, what would be the easiest way of getting around this?
Upvotes: 0
Views: 75
Reputation: 10096
You can do this with the assignment operators +=
and -=
.
This is the same as writing variable = variable + change
or variable = variable - change
const currentAccount = [{
name: 'J.Edge',
balance: 100,
}];
const withdraw = (amount) => {
currentAccount[0].balance -= amount
}
const deposit = (amount) => {
currentAccount[0].balance += amount
}
withdraw(20); // => 100 - 20
deposit(45); // => 80 + 45
console.log(currentAccount[0].balance); // => 125
Note that currentAccount
is an Array, thus you need to access an element in there before changing values.
Upvotes: 1