There are only two hard things in Computer Science: cache invalidation and naming things.
(Source)
Using abbreviations can make code harder to understand, especially on an international team where English may not be everybody's first language.
Thanks to tools like Prettier that can wrap code neatly and readably, we don't have to worry so much about minimizing line width. We can instead prioritize encoding information clearly, accurately, and unambiguously.
Abbreviations | Preferred alternatives |
---|---|
❌ arr |
✅ array |
❌ btn |
✅ button |
❌ cb |
✅ callback |
❌ desc |
✅ description |
❌ e /err |
✅ error |
❌ el |
✅ element |
❌ evt |
✅ event |
❌ fm |
✅ form |
❌ fmt |
✅ format |
❌ k /v |
✅ key /value |
❌ idx |
✅ index |
❌ img |
✅ image |
❌ obj |
✅ object |
❌ opts |
✅ options |
❌ prj |
✅ project |
❌ sm /md /lg |
✅ small /medium /large |
-
i
,j
,k
(when used as loop variables):for (let i = 0; i < students.length; i++) { students[i].enroll(); }
Note: The question of when to use
for
vs alternatives likeArray.prototype.forEach
is a separate topic.Note: Even though
i
,j
,k
are acceptable idiomatic variable names for loops, this doesn't mean that you have to use them; if there is a more descriptive unabbreviated name, feel free to use it:while (remainingTries > 0) { reserveToken(); remainingTries--; }
-
a
,b
(when used as generic values):list.sort((a, b) => { if (a > b) { return 1; } else if (a < b) { return -1; } else { return 0; } });
-
Widely-used acronyms:
// Not `sampleHypetextMarkupLanguage`: const sampleHTML = '<p>Your markup here...</p>'; // Not `homeUniformResourceLocator`: const homeURL = 'http://example.net';
-
x
,y
:In this case,
x
andy
are obviously coordinates in a Canvas, so the abbreviation is good:for (let x = left; x < right; x++) { for (let y = top; y < bottom; y++) { canvas.fillStyle = getRandomStyle(); canvas.fillRect(x, y, x + 1, y + 1); } }
Here
x
andy
are algebraic, so the abbreviation is good:function add(x, y) { return x + y; }
In this counterexample, more descriptive alternative names exist, so the abbreviation is bad:
// `x` and `y` are strings; better names would be `string` and `prefix`: function hasPrefix(x, y) { return x.startsWith(y); }