How to get the Ethereum balance of an address with Web3 JavaScript

In this tutorial, we are going to learn how to get the Ethereum balance of an address with the JavaScript web3 library.

In this tutorial, we are going to learn how to get the Ethereum balance of an address with the JavaScript web3 library.

Note that this also works for all EVM blockchains. Meaning that you can use it to:

  • get the BNB balance on the Binance Smart Chain network
  • get the FTM balance on the Fantom network
  • get the MATIC balance on the Polygon network
  • get the AVAX balance on the Avalanche network

...etc

Here you can find a list of all EVM blockchains: https://chainlist.org/

First, install the web3 library:

npm install web3

and import it:

import Web3 from 'web3';

Now, you need to instantiate Web3 with a provider. It can be an HTTP provider like an Infura URL or another node provider like GetBlock or it can be a wallet that the user connected to your website.

Note that if you use an HTTP provider, you have to pass a URL that corresponds to the blockchain you want to use.

In this example, we use Infura as it supports Ethereum:

const web3 = new Web3(new Web3.providers.HttpProvider(INFURA_URL_HERE));

Then, you can get the balance of an address using that code:

const balance = await web3.eth.getBalance(address);
const etherBalance = web3.utils.fromWei(balance, 'ether');

getBalance will return the balance in a Wei which is a smaller unit than ETH so to make it readable for us, we need to convert it to ETH using the fromWei utility function.

As a reference, 1 ETH = 1000000000000000000 Wei which is 1 * 10 ^ 18. This enables the Ethereum blockchain to have 18 decimals of precision.

Here is a full guide on Units in Ethereum and other EVM networks:

Complete guide: the units used in smart contracts (Uint256, Wei)
In this tutorial, we are going to see the difference between the units used in smart contracts to understand what they correspond to. We’ll talk about UInt256, BigNumber, Wei, Ether and Hex.

And that's it! 👏

Thanks for reading this article!