I am new to Solidity and I am reading Cryptozombies tutorial. I am stuck with mapping part, I understand how it works mapping(key => value) mappingName but I don't understand what is the output of that or where should it be used, I checked videos and articles and still confused. So my question is not about how it works, it is about the purpose of using it.

I am JS coder but is there is a way mapping relevant to .map in JS?


The solidity mapping is use to store the value with the key respectively. Mapping makes the work easy to extract and manage the data. Lets suppose if we want to store some data of the user which is attached with the ethereum address. We can easily use making to map the key value as an ethereum address and data as the structure. Like in below example.

pragma solidity >=0.4.22 <0.6.0;
contract users {

struct userData{
   string fName;
   string lName;

mapping(address => userData) userAddressToData;


Now lets suppose we have 1000 users by using mapping this will be easy to extract the data on the basis of unique ethereum address. Whereas if you use arrays for that you have to create a for loop to compare the values and extract the correct data.


It's like a JavaScript (associative) array. E.g.

var mapping = {};
mapping["foo"] = "bar";

In Solidity, a line like this:

mapping(address => uint256) balances;

creates a variable called balances, where the keys are addresses and the values are numbers (unsigned 256-bit integers). It can be used like this in functions:

balances[0x123abc...] = 5;              // assign a value to a given key
uint256 balance = balances[msg.sender]; // read the value of a given key

Not the answer you're looking for? Browse other questions tagged or ask your own question.