Skip to content

Web3.js Guide — Connecting to Ethereum from JavaScript

DodaTech 1 min read

In this tutorial, you'll learn about Web3.js Guide. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

What You'll Learn

Use the web3.js library to connect a JavaScript app to Ethereum, read data, send transactions, and interact with smart contracts.

Why It Matters

Web3.js is the foundational library for Ethereum dApp development. Understanding it lets you build any Web3 frontend.

Prerequisites

Installation

npm install web3

Connecting to Ethereum

const { Web3 } = require("web3");

// Option 1: Public RPC endpoint (read-only)
const web3 = new Web3(
  "https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY"
);

// Option 2: Browser wallet (MetaMask)
if (window.ethereum) {
  const web3 = new Web3(window.ethereum);
  await window.<a href="/cryptocurrency/ethereum/">Ethereum</a>.enable();
}

Reading Blockchain Data

// Get ETH balance
const balance = await web3.eth.getBalance(
  "0x742d35Cc6634C0532925a3b844Bc9e7595f2bD18"
);
console.log(`${web3.utils.fromWei(balance, "ether")} ETH`);

// Get latest block
const block = await web3.eth.getBlock("latest");
console.log(`Block #${block.number}${block.transactions.length} txs`);

// Get transaction
const tx = await web3.eth.getTransaction(
  "0xabc...123"
);
console.log(tx);

Sending Transactions

const accounts = await web3.eth.getAccounts();
const tx = await web3.eth.sendTransaction({
  from: accounts[0],
  to: "0x...recipient",
  value: web3.utils.toWei("0.01", "ether"),
  gas: 21000,
});
console.log(`Tx hash: ${tx.transactionHash}`);

Interacting with Smart Contracts

const contractABI = [
  // Minimal ERC-20 ABI
  {
    constant: true,
    inputs: [{ name: "_owner", type: "address" }],
    name: "balanceOf",
    outputs: [{ name: "", type: "uint256" }],
    type: "function",
  },
];

const contractAddress = "0xdAC17F958D2ee523a2206206994597C13D831ec7";

const contract = new web3.eth.Contract(
  contractABI,
  contractAddress
);

// Read from contract
const balance = await contract.methods
  .balanceOf("0x...")
  .call();
console.log(`Balance: ${balance}`);

// Write to contract (requires MetaMask)
const result = await contract.methods
  .transfer("0x...recipient", 1000)
  .send({ from: accounts[0] });

Listening to Events

// Listen for Transfer events
contract.events
  .Transfer({ filter: { from: "0x..." } })
  .on("data", (event) => {
    console.log("Transfer event:", event.returnValues);
  })
  .on("error", console.error);

Web3.js vs Ethers.js

Feature Web3.js Ethers.js
Size Larger Smaller (tree-shakeable)
API Callback/Promise Promise-only
TypeScript Limited First-class
ENS Basic Built-in
Popularity Legacy standard Modern standard

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro