0

am writing a function for an account deposit which will return account balance but when i call the function it do return NaN

    deposit(amount){
    let accountBalance;
    accountBalance += amount;
    return accountBalance;
    }
    console.log(accountUser.deposit(2000));
Olabode
  • 1
  • 3
  • Possible duplicate of [Assigning using += gives NaN in javascript](https://stackoverflow.com/questions/28367754/assigning-using-gives-nan-in-javascript) – Heretic Monkey Jun 04 '19 at 23:36

3 Answers3

1

You need to define the value of accountBalance before using a += on it.

let accountBalance = 0;
accountBalance += amount;

This is because undefined + any amount is "Not a Number"

bspates
  • 382
  • 1
  • 10
  • have tried, it actually return a value but not expected one because i have set the accountBalance to 0 before += amount – Olabode Jun 04 '19 at 23:00
  • You'll need to set the accountBalance to whatever the current account balance is. If your trying to use an existing variable named accountBalance defined outside of this function you should remove the the let declaration as that will override the scope. – bspates Jun 04 '19 at 23:02
0

If you set the accountBalance variable as global variable, then you can use that variable inside your deposit function.

var accountBalance = 100;

function deposit(amount){
    accountBalance += amount;
    return accountBalance;
}

console.log(deposit(2000));
Rahul Vala
  • 695
  • 8
  • 17
  • Actually am expecting the accountBalance to increase each time i make a deposit not returning the amount deposited – Olabode Jun 05 '19 at 12:31
0

The type of undefined is a para-primitive of a 'string literal' as opposed to null which is a para-primitive of a 'number primitive' - Therefore a string literal + any other JavaScript Type adds a string representation of its value in expression.

So in case you have a = undefined [which is equally the same as your let a;] declaration, and then using a + 3 is the same as writing "undefined" + 3 and evaluating which is: (string + number ) = NaN; It is quite the contrary with the use of a proper type...: as null is a higher rank of undefined type related to undefined values of real object's it will coerce into a 0 number primitive instead, and evaluate (numerical[empty] + number) = 3, that's actually 0 + 3 = 3. Bekim Bacaj &copy

Therefore you need to make sure you declare at least the correct type variables and propositions before using them in combination and interaction with specific type values.

Bekim Bacaj
  • 5,707
  • 2
  • 24
  • 26