Clean Code Practices in JavaScript Writing code that works is only the baseline requirement. Writing clean, expressive, and maintainable code is what makes you an indispensable software engineer. Here are the core clean code principles applied to modern JavaScript.
Variable and function names should answer three questions: Why does it exist? What does it do? How is it used?
1 // ❌ BAD: Cryptic and meaningless
2 const d = 86400 ;
3 const u = getUsers ( ) ;
4 function chk ( a , b ) { return a > b ; }
5
6 // ✅ CLEAN: Self-documenting
7 const SECONDS_PER_DAY = 86400 ;
8 const activeUsersList = getActiveUsers ( ) ;
9 function isUserEligibleForDiscount ( userAge , minimumAge ) {
10 return userAge >= minimumAge ;
11 }
A function should have a single responsibility. If a function validates input, writes to a database, and formats an email, it should be split into three modular functions:
1 // ❌ BAD: God Function doing 3 unrelated tasks
2 function handleUserSignup ( userData ) {
3 // 1. Validating password...
4 // 2. Inserting into database...
5 // 3. Sending welcome email...
6 }
7
8 // ✅ CLEAN: Modular, testable functions
9 function validateUserCredentials ( credentials ) { /* ... */ }
10 function saveUserToDatabase ( user ) { /* ... */ }
11 function sendWelcomeEmail ( userEmail ) { /* ... */ }
When a function takes 5 or 6 arguments, calling it is error-prone:
1 // ❌ BAD: What order do arguments go in?
2 createUser ( "Sumit" , "Sharma" , "sumit@msk.com" , "Admin" , true , "New Delhi" ) ;
3
4 // ✅ CLEAN: Pass a single configuration object with destructuring!
5 createUser ( {
6 firstName : "Sumit" ,
7 lastName : "Sharma" ,
8 email : "sumit@msk.com" ,
9 role : "Admin" ,
10 isActive : true ,
11 city : "New Delhi"
12 } ) ;
4. Avoid Magic Numbers and Magic Strings A magic number is a hardcoded numerical value with no clear meaning:
1 // ❌ BAD: What does 86400000 mean?
2 setTimeout ( restartServer , 86400000 ) ;
3
4 // ✅ CLEAN: Assign to a named constant!
5 const MILLISECONDS_IN_24_HOURS = 24 * 60 * 60 * 1000 ;
6 setTimeout ( restartServer , MILLISECONDS_IN_24_HOURS ) ;
Instead of mutating arrays with index-based loops and temporary variables, use functional methods (map, filter, reduce):
1 // ❌ BAD: Imperative mutation with temporary array
2 const highScores = [ ] ;
3 for ( let i = 0 ; i < scores . length ; i ++ ) {
4 if ( scores [ i ] >= 80 ) {
5 highScores . push ( scores [ i ] * 1.1 ) ;
6 }
7 }
8
9 // ✅ CLEAN: Declarative, readable transformation
10 const highScores = scores
11 . filter ( score => score >= 80 )
12 . map ( score => score * 1.1 ) ;
Interactive Quiz • Knowledge Check
Practice Quiz According to the Single Responsibility Principle (SRP), what should a function do?
A As many things as possible to save lines of code
B Perform one single task or unit of logic exceptionally well
C Always contain at least 100 lines of code
D Handle both frontend and backend tasks
What is a "magic number" in programming?
A A prime number
B A hardcoded numerical value without clear named context that confuses readers
C A random number generated by Math.random()
D A negative float
Why is passing a single destructured object preferable to having 6 individual positional function arguments?
A Object arguments don't depend on strict parameter order and make function calls self-documenting
B JavaScript only allows up to 3 arguments
C Objects execute twice as fast
D It avoids typing curly braces
Which naming convention is recommended for boolean variables to make them self-documenting?
A Suffix with _num
B Prefix with auxiliary verbs like is, has, can, or should (e.g. isLoading, hasPermission)
C Use ALL CAPS
D Single letters like b
What does the DRY software engineering principle stand for?
A "Do Repeat Yourself"
B "Don't Repeat Yourself" (eliminate duplicate logic through reusable abstractions)
C "Data Routing Year"
D "Deploy React Yesterday"