Mapping in solidity

Hello, I have trouble understanding “mapping” command in Solidity and what it exactly does and why we need it.
Can someone with good understanding help me?

A mapping could be considered like an Object in javascript.

Mapping’s are indexed by a user defined key type, and are technically hash tables. Mappings don’t have a length and are don’t understand if a key is “set” or not.

mapping(string, address) myAccounts;
// Initialise
myAccounts['savings'] = 0xSfg348FAD943;
myAccounts['personal'] = 0xJfS134jdfs28H;
myAccounts['investments'] = 0xKrW334jsksO8H;

Array’s are indexed by a integer value key. They can be much faster and more secure where required, where security is restricting the size of an array. To represent the same Mapping with an Array, we would need to do the following;

address[] accountAddresses;
string[] accountTitles;
// Initialise 
accountAddresses = [0xSfg348FAD943, 0xJfS134jdfs28H, 0xKrW334jsksO8H];
accountTitles = ['savings','personal','investment'];

And then application logic to map the index of accountAddresses to accountTitles, being sure to add and remove items securely to maintain mapping.

So mappings become useful when you want to essentially link two set’s of data.

1 Like

Thank you for your help!