# Clean Coding

Course: [JavaScript](https://www.devtutorials.ai/learn/javascript) · Section: Modules and Clean Coding
Source: https://www.devtutorials.ai/learn/javascript/modules-and-clean-code/clean-coding

> Strict mode and the silent errors it turns into real ones, then modern habits (const and let, ===, no implicit globals, rest parameters) and naming conventions for clean, maintainable code.

## What Is Clean Code?

**Clean code** = code anyone can read, trust and change without worry. Often that "anyone" is you, weeks later.

- **Strict mode** makes JavaScript stop on risky mistakes instead of ignoring them.
- **Modern habits:** `const`/`let`, `===`, rest parameters.
- **Good names:** `orderTotal`, `ShoppingCart`, `MAX_CART_ITEMS`.

**Simple lesson:** clean code makes mistakes obvious and the purpose clear.

### A Real-World Example

A shop function has `totl = 25` (a typo for `total`). In sloppy mode it quietly makes a new global, and the bill shows ₹0.
In strict mode the same line throws `ReferenceError: totl is not defined`, and the bug is fixed in a minute.
A good name like `countPricierThan(catalog, 30)` also tells the next reader what the code does.

<figure className="ts-fig">
  <svg viewBox="0 0 560 170" role="img" aria-label="The same typo goes down two roads. On the sloppy road it slips through silently. On the strict road a barrier stops it with ReferenceError." width="100%">
    <rect x="0" y="0" width="560" height="170" rx="12" fill="#f8fafc" stroke="#e2e8f0" />
    <text x="20" y="50" fontSize="12" fill="#475569">sloppy</text>
    <line x1="80" y1="45" x2="520" y2="45" stroke="#94a3b8" strokeWidth="2" strokeDasharray="6 4" />
    <text y="40" fontSize="12" fontFamily="monospace" fill="#b91c1c">totl = 25<animate attributeName="x" values="90;460" dur="3s" repeatCount="indefinite" /></text>
    <text x="520" y="70" textAnchor="end" fontSize="11" fill="#b91c1c">silent bug: total is 0</text>
    <text x="20" y="125" fontSize="12" fill="#475569">strict</text>
    <line x1="80" y1="120" x2="300" y2="120" stroke="#94a3b8" strokeWidth="2" strokeDasharray="6 4" />
    <rect x="300" y="98" width="200" height="44" rx="8" fill="#1e3a8a" />
    <text x="400" y="125" textAnchor="middle" fontSize="12" fill="#ffffff">ReferenceError: totl</text>
    <text y="115" fontSize="12" fontFamily="monospace" fill="#b91c1c">totl = 25<animate attributeName="x" values="90;220;220" keyTimes="0;0.5;1" dur="3s" repeatCount="indefinite" /></text>
  </svg>
  <figcaption>Strict mode stops the mistake where it happens.</figcaption>
</figure>

These boxes run in sloppy mode on purpose, so you can see both behaviours. To see strict mode, each example puts `"use strict"` at the top of a function.

## What You Will Learn

1. Turning on strict mode, and what it changes.
2. Undeclared variables, `this`, duplicate parameters, modules and classes.
3. `const`/`let` vs `var`, and `===` vs `==`.
4. Avoiding implicit globals, and `...args` vs `arguments`.
5. Meaningful names and naming conventions.

## Introduction to strict mode

**Strict mode** = the same language, but it refuses some risky things. The old, forgiving behaviour is called **sloppy mode**.

### `"use strict"`

A **directive** (an instruction to JavaScript). As the **first** statement of a file or function, it turns strict mode on there.

```js runnable title="The same typo, in a sloppy function and in a strict function"
function sloppyTotal() {
  let total = 0;
  totl = 25; // typo: "totl" instead of "total"
  return total;
}

function strictTotal() {
  "use strict";
  let total = 0;
  try {
    totl = 25; // the same typo, under strict mode
  } catch (error) {
    return `${error.name}: ${error.message}`;
  }
  return total;
}

console.log("strict:", strictTotal());
console.log("sloppy:", sloppyTotal());
```

Expected output:

```text
strict: ReferenceError: totl is not defined
sloppy: 0
```

`"use strict"` works only as the first statement. Anywhere else, it does nothing, with no warning.

### What strict mode changes

<div className="tscroll">

| Situation | Sloppy mode | Strict mode |
|---|---|---|
| Assigning to a name that was never declared | creates a global variable | throws `ReferenceError` |
| Writing to a frozen or read-only property | silently ignored | throws `TypeError` |
| `this` in a plain function call | the global object | `undefined` |
| Two parameters with the same name | allowed, the last one wins | `SyntaxError` |
| The `with` statement | allowed | `SyntaxError` |
| Octal numbers such as `0755` | allowed, means 493 | `SyntaxError` |

</div>

No new features, no slowdown: it only removes risky behaviour.

### Silent errors become actual errors

A **silent error** runs without any message but does the wrong thing. `Object.freeze()` locks an object; sloppy mode ignores the write, strict mode throws.

```js runnable title="Writing to a frozen object, sloppy and strict"
const settings = Object.freeze({ currency: "USD" });

function sloppyUpdate() {
  settings.currency = "EUR";
  return settings.currency;
}

function strictUpdate() {
  "use strict";
  try {
    settings.currency = "EUR";
    return settings.currency;
  } catch (error) {
    return `${error.name}: ${error.message}`;
  }
}

console.log("sloppy:", sloppyUpdate());
console.log("strict:", strictUpdate());
```

Expected output:

```text
sloppy: USD
strict: TypeError: Cannot assign to read only property 'currency' of object '#<Object>'
```

## Common strict mode rules

### Undeclared variables

Assigning without `let`/`const`/`var` makes a global in sloppy mode (it lands on `globalThis`). Strict mode throws.

```js runnable title="An undeclared name becomes a global in sloppy mode"
function saveDiscount() {
  discountRate = 0.1; // no let, const or var
}

saveDiscount();
console.log("discountRate:", discountRate);
console.log("is it global?", "discountRate" in globalThis);

function saveDiscountStrict() {
  "use strict";
  try {
    couponRate = 0.2;
  } catch (error) {
    return error.name;
  }
}

console.log("strict:", saveDiscountStrict());
```

Expected output:

```text
discountRate: 0.1
is it global? true
strict: ReferenceError
```

### `this` in strict mode

A method pulled off its object and called alone: sloppy `this` is the global object (so `undefined` values); strict `this` is `undefined` (a clear `TypeError`).

```js runnable title="A method pulled away from its object"
const customer = {
  firstName: "Asha",
  greetSloppy() {
    return `Hello, ${this.firstName}`;
  },
  greetStrict() {
    "use strict";
    return `Hello, ${this.firstName}`;
  },
};

const greetSloppy = customer.greetSloppy;
const greetStrict = customer.greetStrict;

console.log("called on the object:", customer.greetSloppy());
console.log("sloppy, called alone:", greetSloppy());

try {
  console.log("strict, called alone:", greetStrict());
} catch (error) {
  console.log("strict, called alone:", `${error.name}: ${error.message}`);
}
```

Expected output:

```text
called on the object: Hello, Asha
sloppy, called alone: Hello, undefined
strict, called alone: TypeError: Cannot read properties of undefined (reading 'firstName')
```

### Duplicate parameter names

**Parameter** = a name in a function's brackets. Sloppy mode lets two share a name (the last wins). Strict mode refuses with a `SyntaxError`, before any code runs, so this box builds the functions from text:

```js runnable title="Duplicate parameter names, built from text so the error can be caught"
const sloppyPrice = new Function("price", "price", "return price;");
console.log("sloppy:", sloppyPrice(100, 250));

try {
  new Function("price", "price", '"use strict"; return price;');
} catch (error) {
  console.log("strict:", `${error.name}: ${error.message}`);
}
```

Expected output:

```text
sloppy: 250
strict: SyntaxError: Duplicate parameter name not allowed in this context
```

### Modules and classes automatically use strict mode

**Modules** (files with `import`/`export`) and **class bodies** are always strict.

```js
// cart.js, loaded as a module: already strict, no directive needed
export function addItem(cart, item) {
  total = cart.length; // ReferenceError, because modules are strict
}
```

A class runs here, and shows the same rule:

```js runnable title="A class body is strict, even inside a sloppy code box"
class Cart {
  addItem() {
    itemCount = 1; // undeclared, inside a class method
  }
}

try {
  new Cart().addItem();
} catch (error) {
  console.log("inside a class:", `${error.name}: ${error.message}`);
}
```

Expected output:

```text
inside a class: ReferenceError: itemCount is not defined
```

A plain `<script>` and a CommonJS file (`require`) are still sloppy. Add `"use strict";` as their first line.

## Modern JavaScript best practices

### `const` and `let` vs `var`

`const` cannot be reassigned; `let` can. Both stay inside their **block** (`{ }`). `var` leaks out.

```js runnable title="var escapes its block; let stays inside"
function checkStock(quantity) {
  if (quantity > 0) {
    var messageVar = "in stock";
    let messageLet = "in stock";
  }
  console.log("var outside the block:", messageVar);
  console.log("let outside the block:", typeof messageLet);
}

checkStock(5);

const taxRate = 0.08;
try {
  taxRate = 0.1;
} catch (error) {
  console.log("reassigning a const:", error.name);
}
```

Expected output:

```text
var outside the block: in stock
let outside the block: undefined
reassigning a const: TypeError
```

### `===` vs `==`

`===` (**strict equality**) checks type and value. `==` (**loose equality**) converts first, with surprises.

```js runnable title="Loose equality converts; strict equality does not"
console.log('"" == 0     :', "" == 0);
console.log('"0" == false:', "0" == false);
console.log('"5" == 5    :', "5" == 5);

console.log('"" === 0    :', "" === 0);
console.log('"5" === 5   :', "5" === 5);
console.log("5 === 5     :", 5 === 5);
```

Expected output:

```text
"" == 0     : true
"0" == false: true
"5" == 5    : true
"" === 0    : false
"5" === 5   : false
5 === 5     : true
```

One accepted exception: `value == null` is true for both `null` and `undefined`, and nothing else.

### Avoiding implicit globals

An **implicit global** is made by accident. `let clicks = (views = 0)` declares only `clicks`; `views` leaks. Declare one variable per line.

```js runnable title="A chained assignment that leaks a global"
function resetCounters() {
  let clicks = (views = 0); // only clicks is declared
  return clicks;
}

resetCounters();
console.log("views leaked?", "views" in globalThis);

function resetCountersFixed() {
  let clicks = 0;
  let visits = 0;
  return [clicks, visits];
}

console.log("fixed:", resetCountersFixed());
console.log("visits leaked?", "visits" in globalThis);
```

Expected output:

```text
views leaked? true
fixed: [
  0,
  0
]
visits leaked? false
```

### Rest parameters (`...args`) vs `arguments`

Old code used `arguments` (not a real array). `function total(...prices)` gives a real array, with `reduce`, `map` and `filter`.

```js runnable title="arguments looks like an array but is not one"
function totalOld() {
  console.log("arguments is an array?", Array.isArray(arguments));
  let total = 0;
  for (let i = 0; i < arguments.length; i++) total += arguments[i];
  return total;
}

function totalNew(...prices) {
  console.log("prices is an array?", Array.isArray(prices));
  return prices.reduce((sum, price) => sum + price, 0);
}

console.log("old:", totalOld(20, 35, 15));
console.log("new:", totalNew(20, 35, 15));
```

Expected output:

```text
arguments is an array? false
old: 70
prices is an array? true
new: 70
```

## Writing clean and maintainable code

**Maintainable** = easy to change later. Code is read far more than it is written.

### Meaningful variable names

A name should say what a value holds or what a function does.

```js runnable title="The same function, before and after renaming"
function f(a, b) {
  let r = 0;
  for (const i of a) {
    if (i.p > b) r++;
  }
  return r;
}

function countPricierThan(products, minimumPrice) {
  return products.filter((product) => product.price > minimumPrice).length;
}

const catalog = [
  { name: "Keyboard", price: 45 },
  { name: "Monitor", price: 180 },
  { name: "Mouse", price: 20 },
];
const shortCatalog = catalog.map((item) => ({ p: item.price }));

console.log("f:", f(shortCatalog, 30));
console.log("countPricierThan:", countPricierThan(catalog, 30));
```

Expected output:

```text
f: 2
countPricierThan: 2
```

### Naming conventions

| Convention | Example | Used for |
|---|---|---|
| camelCase | `orderTotal`, `getOrderTotal` | variables and functions |
| PascalCase | `ShoppingCart` | classes |
| UPPER_SNAKE_CASE | `MAX_CART_ITEMS` | fixed values that never change |

#### camelCase

Lowercase first, a capital for each new word. **Why "camel"?** The capitals look like a camel's humps.

#### PascalCase

Like camelCase, but the first letter is a capital too. It tells the reader "use with `new`".

#### UPPER_SNAKE_CASE

Capitals with underscores: a fixed value set once at the top and never changed.

```js runnable title="All three conventions working together"
const MAX_CART_ITEMS = 3;

class ShoppingCart {
  constructor(ownerName) {
    this.ownerName = ownerName;
    this.items = [];
  }

  addItem(productName) {
    if (this.items.length >= MAX_CART_ITEMS) {
      return `Cart is full (${MAX_CART_ITEMS} items)`;
    }
    this.items.push(productName);
    return `Added ${productName}`;
  }
}

const ashaCart = new ShoppingCart("Asha");
for (const productName of ["Keyboard", "Mouse", "Monitor", "Webcam"]) {
  console.log(ashaCart.addItem(productName));
}
```

Expected output:

```text
Added Keyboard
Added Mouse
Added Monitor
Cart is full (3 items)
```

A **linter** (ESLint) warns about `var`, `==` and undeclared names; a **formatter** (Prettier) fixes layout. Set them up once.

## Clean Code on a Web Page

The same feature written cleanly: strict mode, `const`, `===`, a rest parameter and clear names.

```js runnable preview="cart" title="A cleanly written cart"
"use strict";

const MAX_CART_ITEMS = 3;
const PRODUCTS = [
  { name: "Notebook", price: 60 },
  { name: "Steel bottle", price: 299 },
  { name: "Pencil box", price: 120 },
  { name: "Lunch box", price: 349 },
];

class ShoppingCart {
  #items = [];

  add(product) {
    if (this.#items.length === MAX_CART_ITEMS) return false;
    this.#items.push(product);
    return true;
  }

  total() {
    return sumPrices(...this.#items.map((item) => item.price));
  }

  names() {
    return this.#items.map((item) => item.name);
  }
}

function sumPrices(...prices) {
  return prices.reduce((sum, price) => sum + price, 0);
}

const cart = new ShoppingCart();
const shopList = document.querySelector("#shop");

for (const product of PRODUCTS) {
  const button = document.createElement("button");
  button.textContent = `Add ${product.name}`;
  button.addEventListener("click", () => {
    const added = cart.add(product);
    document.querySelector("#cart").innerHTML = cart.names().map((name) => `<li>${name}</li>`).join("");
    document.querySelector("#total").textContent = `₹${cart.total()}`;
    console.log(added ? `Added ${product.name}` : `Cart is full (${MAX_CART_ITEMS} items)`);
  });
  shopList.append(button);
}
```

Add four items: the fourth is refused, and the Console says why.

**Easy way to remember:** **strict**, **const**, **===**, **...rest**, and names that read like sentences.

## TL;DR

- `"use strict"` as the first statement; modules and classes are strict anyway.
- Strict mode turns silent mistakes (typos, frozen writes, lost `this`) into errors.
- `const` by default, `let` when it changes, never `var`; `===`, not `==`.
- Declare every variable; use `...rest` instead of `arguments`.
- camelCase for values and functions, PascalCase for classes, UPPER_SNAKE_CASE for constants.

## Try this

In the undeclared variables box, move `"use strict";` to the top of `saveDiscount()`. The first function now throws a `ReferenceError` too, and nothing leaks to `globalThis`.

## Check Yourself

## Common mistakes

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| `"use strict"` after other code | It works anywhere | Only as the first statement | No effect, no warning |
| `let a = (b = 0)` or a typo | Both are declared | Only `a` is | A global leaks |
| Passing `customer.greet` as a callback | It keeps its object | `this` is lost | `undefined` or a `TypeError` |
| `if (value == 0)` | `==` is fine | Use `===` | `""` and `"0"` match |
| `var` inside a block | It stays inside | It leaks out | Values readable after the block |
| `arguments.map(...)` | It is an array | Use `...prices` | `map is not a function` |

## Quick reference

<div className="tscroll">

| Syntax | Meaning |
|---|---|
| `"use strict";` | turns on strict mode, only as the first statement of a file or function |
| undeclared `name = value` | a global in sloppy mode, a `ReferenceError` in strict mode |
| `this` in a plain call | the global object in sloppy mode, `undefined` in strict mode |
| `function f(price, price)` | allowed in sloppy mode, a `SyntaxError` in strict mode |
| modules and `class` bodies | always strict |
| `const` / `let` | block-scoped variables; `const` cannot be reassigned |
| `===` | compares type and value with no conversion |
| `function f(...prices)` | collects every argument into a real array |
| `orderTotal`, `ShoppingCart`, `MAX_CART_ITEMS` | camelCase, PascalCase, UPPER_SNAKE_CASE |

</div>

## Exercises

## What to Remember

- Let strict mode catch your mistakes.
- Modern habits remove common surprises.
- Good names make code explain itself.

Next: **Performance Optimization**. Debounce, throttle and memoisation: three ways to stop a function doing more work than it needs to.
