Chapter 27 — Build Like a Professional
🎯 Goal (1 line)
Learn the habits and project structure that make your code look like it was written by a professional developer.
This chapter is less about new JavaScript and more about writing JavaScript that other developers enjoy working with. These habits are what interviewers and teammates notice.
The Professional Mindset
Instead of asking:
"Does it work?"
Start asking:
"Would I be happy maintaining this code six months from now?"
Rule #1: Write Small Functions
❌ Bad
const calculateOrder = (cart) => {
// 100 lines of code
};
✅ Better
const calculateSubtotal = (cart) => {};
const calculateTax = (subtotal) => {};
const calculateTotal = (subtotal, tax) => {};
Small functions are:
Easier to test
Easier to debug
Easier to reuse
Rule #2: Use Meaningful Names
❌ Bad
const d = [];
const x = 100;
const a = user.name;
✅ Better
const products = [];
const taxRate = 100;
const userName = user.name;
Imagine a teammate reading your code.
Rule #3: Avoid Repeating Yourself (DRY)
❌ Bad
console.log("Welcome Alice");
console.log("Welcome Bob");
console.log("Welcome John");
✅ Better
const welcome = (name) => {
console.log(`Welcome ${name}`);
};
welcome("Alice");
welcome("Bob");
welcome("John");
Rule #4: Keep Nesting Shallow
❌ Hard to Read
if (user) {
if (user.isLoggedIn) {
if (user.isAdmin) {
console.log("Dashboard");
}
}
}
✅ Better
if (!user || !user.isLoggedIn || !user.isAdmin) {
return;
}
console.log("Dashboard");
Rule #5: Use const by Default
Professional developers usually write:
const
until they actually need
let
Rule #6: Don't Modify Data Unnecessarily
❌
user.name = "John";
✅
const updatedUser = {
...user,
name: "John"
};
This pattern is used constantly in React.
Rule #7: One Responsibility Per Function
❌
const saveUser = () => {
validate();
save();
sendEmail();
updateUI();
};
✅
const validateUser = () => {};
const saveUser = () => {};
const sendWelcomeEmail = () => {};
const updateUserInterface = () => {};
Rule #8: Keep Functions Pure When Possible
A pure function:
takes input
returns output
changes nothing outside
Good
const double = (number) => number * 2;
Avoid functions that secretly modify global variables.
Rule #9: Use Early Returns
Instead of:
if (user) {
if (user.isLoggedIn) {
console.log("Welcome");
}
}
Write:
if (!user) return;
if (!user.isLoggedIn) return;
console.log("Welcome");
Much easier to scan.
Rule #10: Organize Files
Instead of:
project
script.js
Prefer:
project
│
├── index.html
├── css
│ styles.css
│
├── js
│ app.js
│ api.js
│ utils.js
│
└── assets
images
Rule #11: Comment WHY, Not WHAT
❌
// Add two numbers
const total = a + b;
✅
// Backend expects price including tax
const total = price + tax;
Code already explains what.
Comments explain why.
Rule #12: Consistent Formatting
Always indent consistently.
Bad:
if(user){
console.log(user)
}
Good:
if (user) {
console.log(user);
}
Rule #13: Keep Logic Separate From UI
Instead of:
button.addEventListener("click", () => {
const total = price * quantity;
console.log(total);
});
Better:
const calculateTotal = (price, quantity) => price * quantity;
button.addEventListener("click", () => {
console.log(calculateTotal(price, quantity));
});
Now calculateTotal() can be reused anywhere.
MCQs
Q1
Which variable name is better?
A.
const x = 500;
B.
const productPrice = 500;
✅ Answer
B
Meaningful names reduce confusion.
Q2
Which keyword should you use by default?
A. let
B. const
C. var
D. change
✅ Answer
B
Use const unless reassignment is needed.
Q3
Which function is easier to maintain?
A.
const process = () => {
// 200 lines
};
B.
const validate = () => {};
const save = () => {};
const notify = () => {};
✅ Answer
B
Small functions are easier to understand and test.
Q4
Which follows the DRY principle?
A.
console.log("Hi Alice");
console.log("Hi Bob");
B.
const greet = (name) => {
console.log(`Hi ${name}`);
};
✅ Answer
B
Write reusable code instead of repeating yourself.
Q5
Which is a pure function?
A.
let total = 0;
const add = (x) => {
total += x;
};
B.
const add = (a, b) => a + b;
✅ Answer
B
It depends only on its inputs and has no side effects.
Q6
Which comment is more useful?
A.
// Increment i
i++;
B.
// Retry because the API sometimes returns temporary errors
retryCount++;
✅ Answer
B
Explain the reason, not the obvious.
Q7
Which structure is better?
A.
script.js
B.
js/
css/
assets/
✅ Answer
B
Projects grow. Organize early.
Q8
Find the issue.
const update = () => {
validate();
save();
email();
render();
log();
backup();
};
A. Too many responsibilities
B. Missing semicolon
C. Wrong keyword
D. Nothing
✅ Answer
A
One function should have one main job.
Q9
Which code is easier to read?
A.
const d = user.address.city;
B.
const userCity = user.address.city;
✅ Answer
B
Self-explanatory names reduce mental effort.
Q10
Predict the output.
const multiply = (a, b) => a * b;
console.log(multiply(4, 5));
A. 20
B. 45
C. undefined
D. Error
✅ Answer
A
The function returns 4 * 5.
Q11
Which update pattern is preferred in React?
A.
user.age = 30;
B.
const updatedUser = {
...user,
age: 30
};
✅ Answer
B
Create new objects instead of mutating existing ones.
Q12
Which function name is better?
A.
doStuff()
B.
calculateShippingCost()
✅ Answer
B
Names should describe exactly what the function does.
Q13
Which is easier to debug?
A.
One 300-line function.
B.
Ten small functions.
✅ Answer
B
Smaller units isolate problems.
Q14
Find the better version.
A.
if (user) {
if (user.isAdmin) {
dashboard();
}
}
B.
if (!user) return;
if (!user.isAdmin) return;
dashboard();
✅ Answer
B
Early returns reduce nesting and improve readability.
Q15 (Hard)
Which code is more professional?
A
const calc = (a, b) => {
let c = a * b;
return c;
};
B
const calculateArea = (width, height) => width * height;
✅ Answer
B
Why?
Better function name
Better parameter names
Simpler implementation
No unnecessary variable
Mini Coding Challenge
Question
Refactor this code to make it more professional.
const x = (p, q) => {
const r = p * q;
console.log(r);
};
x(20, 5);
Pause before reading the solution.
✅ Answer
const calculateTotalPrice = (price, quantity) => {
const total = price * quantity;
console.log(total);
};
calculateTotalPrice(20, 5);
Improvements:
Function name explains its purpose.
Parameter names are meaningful.
Variable name (
total) is descriptive.Function call is more readable.
Final Mini Project — Product Inventory
Problem
Create a small inventory system.
Each product should have:
{
id,
name,
price,
stock
}
Tasks:
Store three products in an array.
Print all product names.
Find a product by ID.
Increase the stock of one product.
Calculate the total inventory value (
price × stockfor each product).Keep your code clean by using small functions.
✅ One Possible Solution
const products = [
{ id: 1, name: "Laptop", price: 50000, stock: 2 },
{ id: 2, name: "Mouse", price: 800, stock: 10 },
{ id: 3, name: "Keyboard", price: 1500, stock: 5 }
];
const printProductNames = (items) => {
items.forEach(product => console.log(product.name));
};
const findProductById = (items, id) => {
return items.find(product => product.id === id);
};
const increaseStock = (items, id, amount) => {
return items.map(product =>
product.id === id
? { ...product, stock: product.stock + amount }
: product
);
};
const calculateInventoryValue = (items) => {
return items.reduce(
(total, product) => total + product.price * product.stock,
0
);
};
printProductNames(products);
const updatedProducts = increaseStock(products, 2, 5);
console.log(findProductById(updatedProducts, 2));
console.log(calculateInventoryValue(updatedProducts));
✅ Expected Output
Laptop
Mouse
Keyboard
{ id: 2, name: "Mouse", price: 800, stock: 15 }
123500
🎯 Professional Developer Checklist
Before you finish any feature, ask yourself:
✅ Are my variable names meaningful?
✅ Are my functions small (ideally under ~20 lines)?
✅ Does each function have one responsibility?
✅ Did I avoid repeating code?
✅ Did I use
constunless I neededlet?✅ Did I avoid mutating objects/arrays when possible?
✅ Is the code easy to read without extra comments?
✅ Could another developer understand this in 2 minutes?
✅ If I return to this code in 6 months, will I still understand it?
If you can consistently answer "yes" to these questions, you'll be writing code at a professional standard—not just code that works.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.