Skip to main content
JavaScript Basics
CHAPTER 29 Beginner

JavaScript Best Practices

Updated: May 12, 2026
20 min read

# JavaScript Best Practices

Writing code that "works" is only the first step of being a developer. Writing code that is readable, secure, and easily maintainable by other developers is what makes you a professional.

In this chapter, we will summarize the industry-standard best practices that you should apply to every JavaScript project you write.

1. Introduction

As your projects grow from 50 lines of code to 5,000 lines of code, messy habits will catch up with you. "Spaghetti code" (code that is tangled and impossible to follow) leads to bugs that take days to fix.

By adhering to best practices, you ensure that your codebase remains clean, fast, and secure.

2. Learning Objectives

By the end of this chapter, you will be able to:

  • Use consistent naming conventions.
  • Understand the importance of avoiding global variables.
  • Write modular, DRY (Don't Repeat Yourself) code.
  • Optimize DOM manipulation for performance.
  • Use strict mode ("use strict";).
  • Build a Code Refactoring mini-project.

3. The "Use Strict" Directive

The "use strict"; directive was introduced in ECMAScript 5. It tells the browser to execute the code in "strict mode," which throws errors for bad syntax that JavaScript normally allows (like using undeclared variables).

javascript
1234
// Example JavaScript
"use strict";

x = 3.14; // ERROR: x is not defined (Because we didn't use let or const)

*Note: Modern ES6 Modules and Classes automatically run in strict mode, but it is good practice to include it at the top of standard JS files.*

---

4. Real-world Examples & Code Snippets

Example 1: Consistent Naming Conventions

Always use camelCase for variables and functions. Use PascalCase ONLY for Classes. Use UPPERCASE for true constants that never change.

javascript
1234567891011121314151617
// Example JavaScript

// Bad
let first_name = "John";
let UserAge = 30;
function GET_DATA() {}

// Good
let firstName = "John";
let userAge = 30;
function getData() {}

// Class (PascalCase)
class DatabaseConnection {}

// Hardcoded Constants (UPPERCASE)
const MAX_USERS = 100;

Example 2: Avoid Global Variables

Variables declared outside of any function are Global. They can be overwritten by *any* other script on your page (like a third-party analytics plugin), causing unpredictable bugs.

javascript
12345678910111213
// Example JavaScript
// Bad (Global scope)
let count = 0; 
function increment() { count++; }

// Good (Encapsulated inside a function or class)
function counterApp() {
    let count = 0;
    return function() {
        count++;
        return count;
    }
}

Example 3: Use === Instead of ==

The == operator performs type coercion, meaning "5" == 5 is true. This causes massive logical bugs. Always use === (strict equality), which checks both value AND data type.

javascript
123456
// Example JavaScript
// Bad
if (0 == false) { /* This runs! 0 is coerced to false */ }

// Good
if (0 === false) { /* This does NOT run. Number is not a Boolean */ }

Example 4: Write DRY Code (Don't Repeat Yourself)

If you copy and paste the same block of code more than twice, you should turn it into a reusable function.

javascript
12345678910111213
// Example JavaScript
// Bad
let area1 = 10 * 5;
console.log("Area is " + area1);
let area2 = 20 * 5;
console.log("Area is " + area2);

// Good
function printArea(width, height) {
    console.log(`Area is ${width * height}`);
}
printArea(10, 5);
printArea(20, 5);

Example 5: Optimize DOM Manipulations

Querying the DOM (document.getElementById) and modifying the DOM (element.appendChild) are the slowest operations in JavaScript. Do them as rarely as possible.

javascript
12345678910111213
// Example JavaScript
// Bad (Querying DOM 100 times, painting screen 100 times)
for (let i = 0; i < 100; i++) {
    document.getElementById("list").innerHTML += `<li>Item ${i}</li>`;
}

// Good (Query DOM once, build HTML in memory, paint screen once)
const listEl = document.getElementById("list");
let html = "";
for (let i = 0; i < 100; i++) {
    html += `<li>Item ${i}</li>`;
}
listEl.innerHTML = html; // Screen updates exactly once

Example 6: Fail Fast / Early Return

Deeply nested if statements are hard to read. Instead of checking if everything is valid, check if something is INVALID and return early.

javascript
1234567891011121314151617181920
// Example JavaScript
// Bad (Nested)
function processPayment(user) {
    if (user != null) {
        if (user.hasCreditCard) {
            if (user.balance > 0) {
                console.log("Payment processed");
            }
        }
    }
}

// Good (Fail Fast / Early Return)
function processPaymentSafe(user) {
    if (user == null) return;
    if (!user.hasCreditCard) return;
    if (user.balance <= 0) return;
    
    console.log("Payment processed");
}

Example 7: Use Default Parameters

Always account for missing data in your functions to prevent undefined crashing your app.

javascript
1234567891011
// Example JavaScript
// Bad
function calculateTax(price, taxRate) {
    // If taxRate is forgotten, this returns NaN!
    return price + (price * taxRate); 
}

// Good
function calculateTaxSafe(price, taxRate = 0.07) {
    return price + (price * taxRate);
}

Example 8: Commenting Code

Comments should explain *WHY* code does something, not *WHAT* the code does. The code itself should be readable enough to explain the "what".

javascript
12345678
// Example JavaScript
// Bad Comment (Obvious)
// This variable holds the user's age
let age = 25; 

// Good Comment (Explains business logic)
// We add 1 to the index because the external API starts counting at 1, not 0
let userId = arrayIndex + 1; 

Example 9: Magic Numbers

A "magic number" is a hardcoded number in your code with no explanation. Assign it to a well-named const variable.

javascript
1234567891011
// Example JavaScript
// Bad
function calculateDiscount(price) {
    return price * 0.85; // What is 0.85?
}

// Good
const EMPLOYEE_DISCOUNT_RATE = 0.85;
function calculateDiscountSafe(price) {
    return price * EMPLOYEE_DISCOUNT_RATE;
}

Example 10: Avoid Modifying Native Objects

Never add custom methods to native JavaScript objects like String.prototype or Array.prototype. If a future version of JS adds a method with the same name, your website will break entirely.

---

5. Common Mistakes for Beginners

  1. 1. Forgetting to remove console.log(): Leaving dozens of console.log statements in production code slows down the browser and looks unprofessional. Remove them before launching your website.
  1. 2. Writing massive functions: A function should do exactly ONE thing. If a function is validating a form, making an API call, and updating the DOM all at once, it needs to be split into three separate functions.
  1. 3. Ignoring Errors: Writing empty catch(e) {} blocks hides bugs. Always log the error or show a message.

6. Mini Project: Refactoring Bad Code

Let's look at a terrible, messy piece of code, and refactor it into clean, professional code.

The BAD Code:

javascript
12345678910
// BAD JAVASCRIPT
var u = "John";
var t = 100;
function doIt() {
if(u != null) {
if(t > 0) {
document.getElementById(&#039;msg&#039;).innerHTML = "User " + u + " owes $" + t;
}
}
}

The GOOD Code (Refactored):

javascript
1234567891011121314151617181920
// GOOD JAVASCRIPT
"use strict";

const userName = "John";
const amountOwed = 100;

function displayDebtMessage(name, amount) {
    // Early returns for validation
    if (!name) return;
    if (amount <= 0) return;
    
    // Select DOM element once
    const msgElement = document.getElementById("msg");
    
    // Use Template Literals
    msgElement.textContent = `User ${name} owes $${amount}`;
}

// Call the function
displayDebtMessage(userName, amountOwed);

*Why is this better?* We used const, meaningful variable names, early returns to avoid nesting, passed variables as parameters instead of relying on global scope, and used Template Literals.

7. Exercises

  1. 1. Refactor this variable name using camelCase: let myfirstname_is = "Alice";
  1. 2. Refactor this magic number into a constant: if (password.length < 8) { }
  1. 3. Refactor this code to use strict equality: if (userInput == 10) { }

8. MCQs (Multiple Choice Questions)

Q1: What does the "use strict"; directive do? A) Makes the code run faster. B) Prevents the use of undeclared variables and bad syntax. C) Encrypts the JavaScript file. D) Strictly enforces CSS rules. *Answer: B*

Q2: What is "Spaghetti Code"? A) Code written by Italian developers. B) Code that is clean and modular. C) Code that is tangled, unstructured, and hard to maintain. D) Code that deals with arrays and loops. *Answer: C*

Q3: Why is === better than ==? A) It is faster to type. B) It checks for both value equality and data type equality, preventing unexpected type coercion bugs. C) It automatically converts strings to numbers. D) It is required by ES6. *Answer: B*

9. Interview Questions

Q: Explain the concept of DRY in programming. *A: DRY stands for "Don't Repeat Yourself." It is a software development principle aimed at reducing repetition. Instead of duplicating logic in multiple places, you should abstract that logic into a reusable function, class, or module. This makes the code easier to maintain, as a bug only needs to be fixed in one place.*

10. FAQs

Q: Is there a tool that checks for best practices automatically? *A: Yes! Professional developers use a tool called ESLint. It scans your code as you type and throws red underlines if you violate best practices (like forgetting === or leaving unused variables).*

11. Summary

  • Use "use strict"; to catch silent errors.
  • Use camelCase for naming variables and functions.
  • Never use global variables if you can avoid it.
  • Always use === over ==.
  • Keep functions small and focused on a single task (DRY).
  • Use Early Returns to avoid deeply nested if statements.
  • Query the DOM as rarely as possible.

12. Next Chapter Recommendation

Congratulations! You have learned the syntax, the architecture, the asynchronous nature, and the best practices of JavaScript. It is time to put everything together. In the final chapter, Final JavaScript Project, we will build a complete, production-ready web application from scratch.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·