Lesson 4. Added a + on the mapping implementation on the fund() function #1987
-
I noticed that on the FundMe.sol contract, on the fund() function. A + sign is all of the sudden added on the mapping addressToAmountFunded, after Patrick explains about for loop. Is there a difference in execution on the first code |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
Yeah, there is a difference. I suppose visually is easier to understand so I will take a simple example: let a, b;
a = 4;
b = 6;
// The following assigns the value of b to a
a = b; // a = 6 now
// Whereas, the following is equivalent to a = a + b
a += b; // a = 6 + 4, so a = 10 So, in your case addressToAmountFunded[msg.sender] += msg.value;
// The above is equivalent to the following
addressToAmountFunded[msg.sender] = addressToAmountFunded[msg.sender] + msg.value; To sum it up, the |
Beta Was this translation helpful? Give feedback.
-
@davidinci7 Above @krakxn well explained the mathematics behind adding We want everyone to fund our contract along with it we want to trace that which address gives how much amount. So if we use; addressToAmountFunded[msg.sender] = msg.value; Every time an address fund the contract its latest amount will be saved in the mapping. Ex. if the first time an address funds 1 ETH and the next time it funds 2 ETH. The mapping will tell us that the address has only funded 2 ETH because that was the last funded amount but that is not true because the same address has funded a total of 3 ETH. That's what we are doing by using the addressToAmountFunded[msg.sender] += msg.value; This will remember the latest as well as past all funds and will tell that the address has funded a total of 3 ETH. |
Beta Was this translation helpful? Give feedback.
@davidinci7 Above @krakxn well explained the mathematics behind adding
+
. I just want to add the purpose of using+=
instead of=
.We want everyone to fund our contract along with it we want to trace that which address gives how much amount.
So if we use;
Every time an address fund the contract its latest amount will be saved in the mapping. Ex. if the first time an address funds 1 ETH and the next time it funds 2 ETH. The mapping will tell us that the address has only funded 2 ETH because that was the last funded amount but that is not true because the same address has funded a total of 3 ETH. That's what we are doing by using the
+
operator.