Calculating Rectangle Area in JavaScript: Variables and Multiplication in Action
The area of a rectangle exercise is deceptively simple — but it's one of the most important exercises for a beginner. It forces you to practice three essential skills at once: storing values in variables, applying an arithmetic operator to those variables, and printing the result. These same three steps appear in virtually every real-world calculation you'll ever write in JavaScript.
The Formula
Area of a rectangle: area = width × height
In JavaScript, multiplication uses the * operator:
const width = 7;
const height = 3;
const area = width * height;
console.log(area); // 21
Step-by-Step Breakdown
- Lines 1–2: Store the rectangle's dimensions in variables. Descriptive names (
width,height) make the code self-documenting. - Line 4: Multiply the two variables. JavaScript evaluates each variable to its stored value, performs the multiplication, and stores the result in
area. - Line 5: Print the result. Without
console.log(), the calculation happens but nothing is displayed.
Working With Different Number Types
JavaScript handles integers and floats automatically — you don't declare types:
// Integer dimensions:
console.log(5 * 8); // 40
// Float dimensions:
console.log(3.5 * 2); // 7
// Mixed:
console.log(4 * 2.5); // 10 (JavaScript promotes to float when needed)
Wrapping It in a Function
For reusable code, wrap the formula in a function — this is how real programs are structured:
function rectangleArea(width, height) {
return width * height;
}
console.log(rectangleArea(5, 10)); // 50
console.log(rectangleArea(3, 7)); // 21
console.log(rectangleArea(2.5, 4)); // 10
// Real-world use:
const roomWidth = 4.8; // meters
const roomLength = 6.2;
const floorArea = rectangleArea(roomWidth, roomLength);
console.log(`Floor area: ${floorArea.toFixed(1)} m²`); // Floor area: 29.8 m²
Common Mistakes to Avoid
- Using + instead of *:
width + heightgives the wrong answer — area requires multiplication, not addition. - Using undefined variables: Always assign
widthandheightbefore computingarea. - Forgetting console.log(): In JavaScript, calculations don't display unless you explicitly log them.
Key Takeaways
- Store dimensions in clearly named variables; use
*to multiply them. - Area of a rectangle:
area = width * height. - JavaScript works with integers and floats — no type declarations needed.
- Wrap any formula in a function when you'll call it more than once.
What to Learn Next
This exercise combines variables and multiplication — two skills you've now practiced together. Next, try computing areas of other shapes: a triangle (base * height / 2), a circle (Math.PI * radius ** 2). Then explore functions with parameters to make all your geometry calculations reusable, and template literals for clean, formatted output like `Area: ${area} m²`.
