Clean Coding

By Syncfusion®, Inc. · Last updated

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.

sloppy

totl = 25 silent bug: total is 0 strict

ReferenceError: totl totl = 25

Strict mode stops the mistake where it happens.

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.

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:

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

SituationSloppy modeStrict mode
Assigning to a name that was never declaredcreates a global variablethrows ReferenceError
Writing to a frozen or read-only propertysilently ignoredthrows TypeError
this in a plain function callthe global objectundefined
Two parameters with the same nameallowed, the last one winsSyntaxError
The with statementallowedSyntaxError
Octal numbers such as 0755allowed, means 493SyntaxError

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.

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:

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.

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:

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).

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:

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:

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:

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.

// 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:

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:

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.

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:

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.

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:

"" == 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.

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:

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.

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:

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.

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:

f: 2
countPricierThan: 2

Naming conventions

ConventionExampleUsed for
camelCaseorderTotal, getOrderTotalvariables and functions
PascalCaseShoppingCartclasses
UPPER_SNAKE_CASEMAX_CART_ITEMSfixed 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.

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:

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.

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

MistakeWrong ideaCorrect ideaWhat goes wrong
"use strict" after other codeIt works anywhereOnly as the first statementNo effect, no warning
let a = (b = 0) or a typoBoth are declaredOnly a isA global leaks
Passing customer.greet as a callbackIt keeps its objectthis is lostundefined or a TypeError
if (value == 0)== is fineUse ==="" and "0" match
var inside a blockIt stays insideIt leaks outValues readable after the block
arguments.map(...)It is an arrayUse ...pricesmap is not a function

Quick reference

SyntaxMeaning
"use strict";turns on strict mode, only as the first statement of a file or function
undeclared name = valuea global in sloppy mode, a ReferenceError in strict mode
this in a plain callthe 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 bodiesalways strict
const / letblock-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_ITEMScamelCase, PascalCase, UPPER_SNAKE_CASE

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.