How to read private variables?

From smart contract programming / security course, I learned that even if you make a variable private, anyone can view the value because the contract is deployed on a public blockchain.
But how can you actually view the value? External contracts cannot access the value. Or, if you run a node, you can simply view the value?
I don’t understand how it works.

Also, how about mapping?

mapping(address=>uint256) private secretNumber

Is it possible for anyone to view the value of secretNumber without needing to know the address?

PS: I’m not trying to store any sensitive information on blockchain but I am just curios.

I asked this in different community, here’s what I found.

You can private variables using web3.js in Node.js. For example, if you know the variable is stored in slot#2:

web3.eth.getStorageAt(contractAddress, 2, (a) => {
  console.log(a)
});

Slot number is determined by the order of declared state variables (however, one slot has 32bytes limit).

Check this article:
https://cryptomarketpool.com/access-private-data-on-the-eth-blockchain/

This video explains how to access private variable in detail:
https://www.youtube.com/watch?v=Gg6nt3YW74o&ab_channel=SmartContractProgrammer

1 Like