Overview

Ethers.js and Web3.js are both JavaScript libraries that allow developers to interact with the Ethereum blockchain. However, they differ in design philosophy, size, performance, and ease of use.

Key Differences

  • Size and Performance:
    • Ethers.js: Lightweight and modular, making it easy to include in projects.
    • Web3.js: Larger in size, as it includes more built-in features.
  • TypeScript Support:
    • Ethers.js: Fully built with TypeScript, providing strong type definitions.
    • Web3.js: Primarily written in JavaScript, with some TypeScript support.
  • User-Friendly API:
    • Ethers.js: Simpler and more intuitive API.
    • Web3.js: More complex, which can be overwhelming for beginners.
  • Provider and Signer:
    • Ethers.js: Separates provider (for reading data) and signer (for sending transactions).
    • Web3.js: Combines provider and signer functionalities.
  • Documentation:
    • Ethers.js: Clear and concise documentation.
    • Web3.js: Extensive but can be overwhelming.

Ethers.js Example


<div class="example">
<label for="ethersAddress">Enter Ethereum Address:</label>
<input type="text" id="ethersAddress" placeholder="0x...">
<button id="getEthersBalance">Get Balance</button>
<h3>Balance: <span id="ethersBalance">0</span> ETH</h3>
</div>

<script>
const provider = new ethers.providers.getDefaultProvider('homestead');

document.getElementById('getEthersBalance').onclick = async () => {
const address = document.getElementById('ethersAddress').value;
try {
const balance = await provider.getBalance(address);
const balanceInEther = ethers.utils.formatEther(balance);
document.getElementById('ethersBalance').innerText = balanceInEther;
} catch (error) {
console.error(error);
alert('Error fetching balance. Please check the address and try again.');
}
};
</script>

Web3.js Example


<div class="example">
<label for="web3Address">Enter Ethereum Address:</label>
<input type="text" id="web3Address" placeholder="0x...">
<button id="getWeb3Balance">Get Balance</button>
<h3>Balance : <span id="web3Balance">0</span> ETH</h3>
</div>

<script>
// Initialize Web3
if (typeof window.ethereum !== 'undefined') {
const web3 = new Web3(window.ethereum);
window.ethereum.request({ method: 'eth_requestAccounts' });
} else {
alert('Please install MetaMask!');
}

document.getElementById('getWeb3Balance').onclick = async () => {
const address = document.getElementById('web3Address').value;
try {
const balance = await web3.eth.getBalance(address);
const balanceInEther = web3.utils.fromWei(balance, 'ether');
document.getElementById('web3Balance').innerText = balanceInEther;
} catch (error) {
console.error(error);
alert('Error fetching balance. Please check the address and try again.');
}
};
</script>