| 1 | Use const by default | Prevents accidental reassignment. | const userName = "John"; |
| 2 | Use let only when reassignment is needed | Makes changing values clear. | let count = 0; count = count + 1; |
| 3 | Avoid var | Prevents function-scope and hoisting confusion. | const total = 100; |
| 4 | Use strict equality | Avoids unexpected type coercion. | if (age === 18) { console.log("Adult"); } |
| 5 | Use descriptive variable names | Makes code easier to understand. | const totalPrice = price + tax; |
| 6 | Use camelCase for variables | Matches common JavaScript style. | const firstName = "John"; |
| 7 | Use PascalCase for classes | Improves class readability. | class UserProfile { } |
| 8 | Keep functions small | Makes testing and debugging easier. | function add(a, b) { return a + b; } |
| 9 | Use one responsibility per function | Improves maintainability. | function validateEmail(email) { return email.includes("@"); } |
| 10 | Return values instead of mutating globals | Reduces side effects. | function getTotal(a, b) { return a + b; } |
| 11 | Avoid global variables | Prevents naming conflicts. | const appConfig = { theme: "dark" }; |
| 12 | Use modules | Keeps code organized. | import { formatDate } from "./utils.js"; |
| 13 | Use default parameters | Prevents undefined arguments. | function greet(name = "Guest") { return name; } |
| 14 | Use destructuring carefully | Reduces repetitive property access. | const { name, email } = user; |
| 15 | Use spread for immutable updates | Avoids accidental mutation. | const updatedUser = { ...user, active: true }; |
| 16 | Use array methods where readable | Improves data transformation clarity. | const names = users.map(user => user.name); |
| 17 | Use filter for selection | Makes filtering intent clear. | const activeUsers = users.filter(user => user.active); |
| 18 | Use reduce for totals | Combines values into one result. | const total = prices.reduce((sum, price) => sum + price, 0); |
| 19 | Always provide reduce initial value | Prevents errors with empty arrays. | items.reduce((total, item) => total + item.price, 0); |
| 20 | Use optional chaining | Safely reads nested properties. | const city = user.address?.city; |
| 21 | Use nullish coalescing | Provides fallback only for null or undefined. | const limit = settings.limit ?? 10; |
| 22 | Handle errors with try catch | Prevents app crashes. | try { runTask(); } catch (error) { console.log(error.message); } |
| 23 | Use finally for cleanup | Runs cleanup after success or failure. | try { load(); } finally { hideLoader(); } |
| 24 | Throw Error objects | Preserves useful debugging details. | throw new Error("Invalid input"); |
| 25 | Use async await for readable async code | Improves async flow readability. | const users = await fetchUsers(); |
| 26 | Handle async errors | Prevents unhandled promise rejections. | try { await fetchUsers(); } catch (error) { showError(); } |
| 27 | Use Promise.all for parallel tasks | Improves performance for independent tasks. | const data = await Promise.all([getUsers(), getOrders()]); |
| 28 | Check fetch response.ok | Handles HTTP errors properly. | if (!response.ok) { throw new Error("Request failed"); } |
| 29 | Use JSON.stringify for storage | Stores objects safely as strings. | localStorage.setItem("user", JSON.stringify(user)); |
| 30 | Use JSON.parse safely | Prevents crashes from invalid JSON. | try { JSON.parse(text); } catch (error) { console.log("Invalid JSON"); } |
| 31 | Use textContent for plain text | Safer than innerHTML for text updates. | message.textContent = "Saved successfully"; |
| 32 | Avoid unsafe innerHTML | Reduces XSS security risks. | element.textContent = userInput; |
| 33 | Use classList for CSS classes | Keeps style changes clean. | modal.classList.add("show"); |
| 34 | Use addEventListener | Separates behavior from HTML. | button.addEventListener("click", handleClick); |
| 35 | Use event delegation | Improves performance for dynamic lists. | list.addEventListener("click", function(event) { console.log(event.target); }); |
| 36 | Clean up timers | Prevents memory and logic issues. | clearInterval(intervalId); |
| 37 | Debounce frequent events | Improves performance for search and resize. | clearTimeout(timer); timer = setTimeout(search, 300); |
| 38 | Use requestAnimationFrame for animations | Improves rendering performance. | requestAnimationFrame(animate); |
| 39 | Validate user input | Prevents invalid data processing. | if (email === "") { showError("Email is required"); } |
| 40 | Do not trust frontend validation only | Improves security. | // Validate again on the server |
| 41 | Avoid storing secrets in frontend | Protects sensitive data. | // Keep API secrets on the server |
| 42 | Avoid sensitive data in localStorage | Reduces security risk. | sessionStorage.removeItem("token"); |
| 43 | Use meaningful error messages | Improves debugging and user experience. | throw new Error("User ID is required"); |
| 44 | Keep conditions readable | Makes logic easier to maintain. | if (user.active && user.emailVerified) { allowAccess(); } |
| 45 | Avoid deeply nested code | Improves readability. | if (!user) { return; } |
| 46 | Use early returns | Simplifies control flow. | if (!isValid) { return; } |
| 47 | Comment why, not what | Documents reasoning instead of obvious code. | // Keep retry low to avoid API rate limits |
| 48 | Use linting | Catches common bugs early. | // ESLint helps enforce code quality |
| 49 | Write tests for important logic | Prevents regressions. | expect(add(2, 3)).toBe(5); |
| 50 | Keep code consistent | Improves teamwork and maintainability. | // Use Prettier for consistent formatting |