Created
June 16, 2018 08:38
-
-
Save zailleh/f1a3548a9fdeab74d0278e15c3a76ec5 to your computer and use it in GitHub Desktop.
array.push example.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//create empty array of bank accounts | |
let bankAccounts = [] | |
// function to create a new account | |
const addAccount = function( name, amount ) { | |
// create new account object | |
let newAccount = { | |
accountName: name, | |
balance: amount | |
}; | |
// push returns new length of the array after push operation | |
// push new object into accounts array, storing the number of accounts | |
const numAccounts = bankAccounts.push( newAccount ); | |
// since arrays are 0 indexed, length is always 1 more than the last index | |
// (eg, last item in array is array.length - 1, subtract one from numAccounts | |
// to get the index of the account in the array | |
const accountNumber = numAccounts - 1; | |
return accountNumber; | |
}; | |
// function to deposit into account | |
const deposit = function ( accountNo, amount ) { | |
// access the bank account deposit and add the new amount | |
newBalance = bankAccounts[ accountNo ].balance + amount; | |
// store it back into the account balance | |
bankAccounts[ accountNo ].balance = newBalance; | |
}; | |
// create a new account and keep the account number | |
const newAccountNo = addAccount( 'testAccount', 100 ); // newAccountNo == 0 (first item in array) | |
// deposit more into the new account | |
deposit( newAccountNo, 100 ); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment