Ethers.js vs web3.js: Key Differences and When to Use Each
Ethers.js and web3.js are popular JavaScript libraries for interacting with Ethereum blockchain. Ethers.js is lighter, more modular, and easier to use, while web3.js is older with broader support but heavier and more complex.Quick Comparison
Here is a quick side-by-side comparison of Ethers.js and web3.js based on key factors.
| Factor | Ethers.js | web3.js |
|---|---|---|
| Library Size | Smaller and modular (~100 KB) | Larger and monolithic (~300 KB) |
| API Style | Modern, promise-based, clean | Older, callback and promise support |
| Documentation | Clear and beginner-friendly | Comprehensive but complex |
| Community & Support | Growing rapidly | Mature and widely used |
| Features | Built-in utilities for wallets and ENS | More legacy features and plugins |
| Compatibility | Works well with modern frameworks | Supports older projects and tools |
Key Differences
Ethers.js focuses on simplicity and modularity. It uses modern JavaScript features like promises and async/await, making code easier to read and write. Its smaller size helps reduce app bundle size, which is great for web apps.
web3.js is older and more feature-rich but can feel bulky. It supports callbacks and promises, which can confuse beginners. It also includes many legacy features that may not be needed in new projects.
Another difference is in wallet and provider management: ethers.js has built-in wallet utilities and better ENS (Ethereum Name Service) support, while web3.js relies more on external plugins. Overall, ethers.js is more modern and easier for new developers, while web3.js is better for legacy support and complex use cases.
Code Comparison
This example shows how to get the current Ethereum block number using ethers.js.
import { ethers } from "ethers"; async function getBlockNumber() { const provider = new ethers.providers.JsonRpcProvider("https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID"); const blockNumber = await provider.getBlockNumber(); console.log("Current block number:", blockNumber); } getBlockNumber();
web3.js Equivalent
Here is the same task done with web3.js to get the current block number.
import Web3 from "web3"; async function getBlockNumber() { const web3 = new Web3("https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID"); const blockNumber = await web3.eth.getBlockNumber(); console.log("Current block number:", blockNumber); } getBlockNumber();
When to Use Which
Choose ethers.js when you want a modern, lightweight library with easy-to-use APIs and good wallet support, especially for new projects or web apps. It helps keep your code clean and your app size small.
Choose web3.js if you are working on legacy projects that already use it or need some of its specific plugins and features. It is also a solid choice if you want a mature library with a large community and extensive documentation.