1.2 Module 1 · Operators, Methods & Keywords

JavaScript Best Practices

Learn the recommended coding standards and techniques that separate clean, maintainable code from code that creates future headaches.

1

Definition

JavaScript Best Practices are recommended coding standards and techniques used to write clean, efficient, maintainable, and error-free code.

They are not enforced by the language itself — but following them makes your code easier to read, debug, and scale over time.

2

Simple Way

Best practices mean: "Write code in a way that future you (and others) won't hate you."

Read Easy to read — clear names, tidy structure
Debug Easy to debug — isolated logic, no global side-effects
Scale Easy to scale — reusable functions, no repeated code
3

Code Examples

Example 1 — Clean vs Messy Code
Bad Code

Single-letter names tell you nothing about what the code does.

let a = 10;
let b = 20;
let c = a + b;
console.log(c);
Output
Click ▶ Run to execute
Good Code — meaningful variable names
let firstNumber = 10;
let secondNumber = 20;
let totalSum = firstNumber + secondNumber;

console.log(totalSum);
Output
Click ▶ Run good code
Explanation
  • Meaningful variable names improve readability instantly
  • Code becomes self-explanatory — no comments needed
Example 2 — Avoid Global Variables
Bad Practice

count lives globally — any part of the program can accidentally change it.

var count = 0;

function increment() {
    count++;
}

increment();
console.log(count);
Output
Click ▶ Run to execute
Good Practice — keep variables in local scope
function increment() {
    let count = 0;
    count++;
    console.log(count);
}

increment();
Output
Click ▶ Run good code
Explanation
  • Global variables can be modified from anywhere — a source of hard-to-trace bugs
  • Use local scope (let / const inside a function) for safety
Example 3 — Code Optimization
Inefficient

The string "Hello" is re-evaluated as a literal on every iteration.

for (let i = 0; i < 5; i++) {
    console.log("Hello");
}
Output
Click ▶ Run to execute
Better — store the value once, reuse it
let message = "Hello";

for (let i = 0; i < 5; i++) {
    console.log(message);
}
Output
Click ▶ Run better code
Explanation
  • Store repeated values in a variable — avoids redundant work
  • More important when the value is computed (e.g. a function call)
4

Real-Life Example

Imagine writing notes for exams:

📝
Messy notes → you struggle to revise later
Clean notes → easy to understand and review
🔁
Repeated info → waste of time and space
💡
Clean code today = less headache tomorrow
5

HTML + JavaScript Example

Best practices shine in real HTML pages too. Notice the function, clear naming, and input validation below. Click ▶ Preview to run it live.

Live in Browser
<!DOCTYPE html>
<html>
<head><title>Best Practices</title></head>
<body style="font-family:sans-serif;padding:20px;background:#f8f9fa">

  <h2>User Greeting</h2>
  <p id="output"></p>

  <script>
    function greetUser(userName) {
        if (!userName) {
            return "Hello, Guest";
        }
        return "Hello, " + userName;
    }

    let name = "Aman";
    document.getElementById("output").innerText = greetUser(name);
  </script>

</body>
</html>
Live Preview
What's good here
  • Function used instead of repeated inline code
  • Clear, descriptive naming (greetUser, userName)
  • Input validation — handles missing name gracefully
6

Tasks (Practice)

Easy Task 1 — Rename for clarity
Starter code
let x = 5;
let y = 10;
let z = x * y;
console.log(z);
  • Rewrite using meaningful variable names
  • The variables represent a width, height, and area
Medium Task 2 — Remove global variable
Starter code — needs fixing
var total = 0;

function add() {
    total += 10;
}
  • Remove the global total variable
  • Make add() self-contained and return the result
  • Print the return value with console.log()
7

MCQs

Q1
Which is a good variable name?
  • A x
  • B data
  • C totalPrice
  • D a1
💡 C is correct. Descriptive names like totalPrice make the purpose immediately obvious — no guessing required.
Q2
Why should we avoid global variables?
  • A They are faster
  • B They cause bugs and conflicts
  • C They reduce code size
  • D No reason
💡 B is correct. Global variables can be modified from anywhere in the program, making bugs very hard to trace.
Q3
What is clean code?
  • A Short code
  • B Fast code
  • C Readable and maintainable code
  • D Complex code
💡 C is correct. Clean code focuses on clarity and structure — it should be easy for anyone (including future you) to read and change.
8

Pro Tips & Extra Knowledge

  • 01

    Use let and const instead of var. var has function scope and hoisting quirks that cause subtle bugs.

    Prefer let / const
    const MAX_SCORE = 100;   // value never changes
    let currentScore = 0;    // value will change
    
    console.log(MAX_SCORE, currentScore);
    Output
    Click ▶ Run to execute
  • 02

    Follow camelCase naming conventions for variables and functions:

    Naming conventions
    // camelCase — variables and functions
    let userName = "Aman";
    function calculateTotal() {}
    
    // UPPER_SNAKE_CASE — constants
    const MAX_RETRIES = 3;
  • 03

    Keep functions small and focused — each function should do one thing only. This makes testing and debugging dramatically easier.

  • 04

    Follow the DRY principle — Don't Repeat Yourself. If you copy-paste code more than once, put it in a function.

    DRY in action
    function greet(name) {
        console.log("Hello, " + name + "!");
    }
    
    greet("Aman");
    greet("Sara");
    greet("Ali");
    Output
    Click ▶ Run to execute
Mini Challenge

Spot the best-practice violation — then think about how you'd improve it before revealing the answer.

What's wrong with this code?
let a = 10;

function test() {
    a = 20;
}

test();
console.log(a);
Output
Think first, then run!
What's Wrong & How to Fix It
// Problem:
// 'a' is a global variable — test() silently mutates it.
// This is hard to track in larger codebases.

// Output of original: 20  (a was changed globally)

// Improved version — no global mutation:
function test() {
    let a = 20;       // local to this function
    console.log(a);   // prints 20
}

test();
// The outer 'a' is untouched — safe and predictable.
1.1 Operators & Debugging