Jess Jess - 3 months ago 12
Javascript Question

"TypeError: Cannot read property 'balance' of undefined". Not sure what is wrong

When I run it, I get "TypeError: Cannot read property 'balance' of undefined."
I'm new to learning Node, and I'm not sure what I'm doing wrong. Please help.

Does it have something to do with scope? How should I fix it?



//create an accounts array:
var accounts = [];

// create a function that allows you to create an account, passing it an account object:
function createAccount(account)
{
accounts.push(account);
return account;
}

// create a function that allows you to lookup an account by passing it a username:
function getAccount(userName)
{
var matchedAccount;

for (var i = 0; i < accounts.length; i++)
{
if (accounts[i] === userName)
{
matchedAccount = accounts[i];
}
}

return matchedAccount;
}

// create a function called deposit:
function deposit(account, amount)
{
if (typeof amount === "number")
{
account.balance = (account.balance + amount);
}
else
{
console.log("Deposit failed. Amount is not a number.")
}
}

// create a function called withdrawal:
function withdraw(account, amount)
{
if (typeof amount === "number")
{
account.balance = (account.balance - amount);
}
else
{
console.log("Withdraw failed. Amount is not a number.")
}
}

// create a function called getBalance, which will return the current balance of the account passed to it:
function getBalance(account)
{
return account.balance;
}

function createBalanceGetter(account)
{
return function()
{
return account.balance;
}
}

var jessica = createAccount(
{
userName: "Jessica",
balance: 0
});

deposit(jessica, 120);
withdraw(jessica, 10);

var jessica2 = getAccount("Jessica");
var getJessica2Balance = createBalanceGetter(jessica2);

console.log(getJessica2Balance());





Answer

In your getAccount, you must search for accounts[i].userName, not just accounts[i]. Change the getAccount function to this:

function getAccount(userName)
{
    var matchedAccount;

    for (var i = 0; i < accounts.length; i++)
    {
        if (accounts[i].userName === userName)
        {
            matchedAccount = accounts[i];
        }
    }

    return matchedAccount;
}

Now this does a linear search on each account, and compares the account's userName to the given username. Before, you were comparing an the account object to a string, which is incorrect. This caused createBalanceGetter to try to access undefined.balance, which gives the error. Here's a fiddle.