Code Style - Javascript
Prefix booleans with is
, has
, or can
Section titled “Prefix booleans with is, has, or can”✅ const isReady = true;❌ const ready = true;
✅ const hasChildren = true;❌ const children = true;
✅ const canSubmit = true;❌ const submit = true;
// always stay positive❌ const isNotReady = false;❌ const isNoActiveUser = true;
Template string/literals
Section titled “Template string/literals”let firstName = "John";let lastName = "Doe";
'Welcome ' + firstname + ' ' + lastName + '!'; `Welcome ${firstName} ${lastName}!`;
Use const/let
Section titled “Use const/let” var name = "John"; const name = "John";
var age = 30; let age = 30;
// always use const unless you know the variable will be re-assignedconst name = "John";name = "Jane"; // ❌ TypeError: Assignment to constant variable.
let age = 30;age = 31; // ✅
Creating new Objects/Arrays
Section titled “Creating new Objects/Arrays”const settings = new Object();const settings = {};
const users = new Array();const users = [];
Arrow functions
Section titled “Arrow functions”// bad[1, 2, 3].map(function (x) {const y = x + 1;return x * y;});
// good[1, 2, 3].map((x) => {const y = x + 1;return x * y;});
Avoid single letter names
Section titled “Avoid single letter names”Try to avoid one character names unless it’s a loop, a counter or in a reducer.
// badconst x = 'John Doe';
// goodforeach (let i in items) {console.log(i);}
//good.reduce((a, b) => a + b, 0);
// badfunction q() {// ...}
// goodfunction query() {// ...}
Be descriptive
Section titled “Be descriptive”Try to be as descriptive as possible with your variable names. Don’t be afraid to use long variable names as long as they are descriptive.
// badconst update = () => {// ...}
// badconst xyz = 'John Doe';
// goodconst updateUser = () => {// ...}
// goodconst fullName = 'John Doe';
Do not include filename extensions
Section titled “Do not include filename extensions”// badimport foo from './foo.js';import bar from './bar.jsx';import baz from './baz/index.astro';
// goodimport foo from './foo';import bar from './bar';import baz from './baz';
Comparison operators
Section titled “Comparison operators”Use ===
and !==
over ==
and !=
// badif (isValid === true) {// ...}
// goodif (isValid) {// ...}
// badif (name) {// ...}
// goodif (name !== '') {// ...}
// badif (collection.length) {// ...}
// goodif (collection.length > 0) {// ...}
FIXME/TODO
Section titled “FIXME/TODO”// FIXME:
to annotate a problem
// FIXME: shouldn’t use a global heretotal = 0;
// TODO:
to annotates a solution to a problem
// TODO: total should be configurable by an options paramthis.total = 0;