At first glance, Solidity looks comfortably familiar. It has curly braces, function declarations, familiar control structures, and an inheritance model that looks like classical OOP. But treating the Ethereum Virtual Machine (EVM) like a Node.js runtime is the fastest way to write gas-guzzling, easily hackable smart contracts.
The Illusion of Familiarity
Solidity was deliberately engineered with ECMAScript-like syntax to ease developer onboarding in Ethereum’s early days. It worked—hundreds of thousands of web developers transitioned to Web3.
However, the underlying execution environment has nothing in common with JavaScript:
- JavaScript runs in an abundant, sandboxed runtime (V8, browser) with automatic garbage collection, dynamic typing, asynchronous event loops, and virtually unlimited memory.
- Solidity runs in a constrained, deterministic, metered state machine (the EVM) where every instruction costs real currency, memory is ephemeral, state changes are permanent, and execution must halt within a strict block gas limit.
When you copy-paste your mental models from JavaScript to Solidity, disaster strikes. Here are the most critical mistakes developers make—and how to fix them.
1. The Unbounded Loop: A Fatal Architectural Flaw
In JavaScript, iterating over an array of users is standard practice:
// JavaScript / TypeScript: Harmless
function payAllUsers(users) {
users.forEach(user => {
paymentService.transfer(user.wallet, user.amount);
});
}
Bring this pattern into Solidity, and you create an immediate Denial of Service (DoS) vulnerability:
// Solidity: CRITICAL BUG
function distributeRewards(address[] memory recipients) external onlyOwner {
for (uint256 i = 0; i < recipients.length; i++) {
token.transfer(recipients[i], 100);
}
}
Why it fails:
The EVM enforces a Block Gas Limit (typically around 30 million gas on Ethereum mainnet). If your array grows to several thousand recipients, the transaction requires more gas than a single block can accommodate. The function becomes permanently uncallable, locking contract funds forever.
The Fix: The Pull-Over-Push Pattern
Never batch state-mutating payouts in a single loop. Instead, track balances internally and make the users pay their own gas to withdraw:
// The Idiomatic Web3 Way: Pull Pattern
mapping(address => uint256) public balances;
function claimReward() external {
uint256 reward = balances[msg.sender];
require(reward > 0, "No rewards available");
balances[msg.sender] = 0;
token.transfer(msg.sender, reward);}
2. Ignoring the Storage Hierarchy (SLOAD & SSTORE)
In JavaScript, variable lookup costs are functionally equivalent whether you access an object property or a local variable. In Solidity, accessing contract storage is brutally expensive.
- Memory / Stack: Very cheap (single-digit gas for reads/writes).
- Storage (Warm SLOAD): 100 gas.
- Storage (Cold SLOAD): 2,100 gas.
- Storage (SSTORE): Up to 20,000 gas.
<h3>The "JavaScript" Way (Wasting Massive Gas):</h3>
<pre><code class="language-solidity">contract GasWaster {
uint256 public totalScore; // Stored in contract storage
// Reading & writing from storage on every iteration
function calculate(uint256[] calldata scores) external {
for (uint256 i = 0; i < scores.length; i++) {
totalScore += scores[i]; // SLOAD + SSTORE executed every cycle!
}
}
}
<h3>The Idiomatic Solidity Way:</h3>
<p>
Cache values in the stack/memory, operate on them, and write to storage only once:
</p>
<pre><code class="language-solidity">contract GasOptimizer {
uint256 public totalScore;
function calculate(uint256[] calldata scores) external {
uint256 tempTotal = totalScore; // Single SLOAD
for (uint256 i = 0; i < scores.length; i++) {
tempTotal += scores[i]; // Operates on the stack
}
totalScore = tempTotal; // Single SSTORE
}
}
3. The Floating-Point Delusion: Precision Loss
JavaScript handles all numbers using IEEE 754 double-precision floating points (until you hit BigInt). You can naturally calculate percentages like amount * 0.05.
Solidity has zero native floating-point math. If you divide 3 / 4, Solidity returns 0 due to integer truncation.
<h3>The Truncation Trap:</h3>
<pre><code class="language-solidity">// BROKEN: Precision truncated to 0 immediately
function calculateFee(uint256 amount) public pure returns (uint256) {
return (amount / 100) 5; // If amount is 99, 99 / 100 = 0. 0 5 = 0.
}
<h3>The Solidity Principle: Multiply Before Dividing</h3>
<pre><code class="language-solidity">// FIXED: Multiply first, divide last
function calculateFee(uint256 amount) public pure returns (uint256) {
return (amount 5) / 100; // (99 5) / 100 = 495 / 100 = 4
}
Always scale up integers (using basis points or fixed-point libraries like OpenZeppelin’s Math or PRBMath) before performing division.
4. Confusing “Private” with “Secret”
In modern JS/TS, a private field (#privateField) or closure hides data from external execution contexts. It is inaccessible outside the class or module.
In Solidity, the private keyword only means other smart contracts cannot read this variable directly via internal ABI interfaces.
Golden Rule: Everything on a public blockchain is visible to anyone running a node.
Marking a private key, password, or hidden game state as private does not encrypt it. Anyone can inspect your contract’s raw storage slots via eth_getStorageAt and retrieve the byte values in seconds.
5. Procedural Execution vs. The Reentrancy Vector
In JS, function execution occurs within a single-threaded event loop. If you call an external API, execution pauses until a promise resolves (or runs asynchronously in microtasks). You rarely worry about that API intercepting the code execution flow and hijacking the originating module mid-function.
In the EVM, an external call (e.g., sending native ETH via call) hands full execution control over to the recipient contract’s receive() or fallback() hook.
<pre><code class="language-solidity">// DANGEROUS: Standard procedural flow
function withdraw() external {
uint256 balance = balances[msg.sender];
require(balance > 0);
// External call transfers execution to the caller
(bool success, ) = msg.sender.call{value: balance}("");
require(success);
// State updated AFTER interaction (vulnerable to reentrancy!)
balances[msg.sender] = 0;
}
<p>
Before the balance is zeroed out, an attacker's fallback function calls <code>withdraw()</code> again. The balance check passes a second time, draining the protocol.
</p>
<p>
You must replace procedural logic with the <strong>Checks-Effects-Interactions (CEI)</strong> pattern, or utilize a reentrancy guard:
</p>
<pre><code class="language-solidity">// SAFE: Checks-Effects-Interactions
function withdraw() external {
// 1. Checks
uint256 balance = balances[msg.sender];
require(balance > 0, “No balance”);
// 2. Effects (State changes made FIRST)
balances[msg.sender] = 0;
// 3. Interactions (External calls made LAST)
(bool success, ) = msg.sender.call{value: balance}("");
require(success, "Transfer failed");
}
The Paradigm Shift
Writing smart contracts is not application development—it is closer to hardware-level architecture combined with defensive financial accounting.
To write professional-grade Solidity, ditch your Web2 heuristics:
- Forget rapid prototyping with nested dynamic structures; optimize for packed 32-byte storage slots.
- Forget unbounded collection iteration; construct decentralized, pull-based claiming mechanisms.
- Assume every external interaction is hostile and actively attempting to manipulate your state.
Solidity’s syntax was designed to welcome you in. Now it’s time to shed the JavaScript mindset and respect the realities of the EVM.