Skip to content

Code Style - Javascript

booleans.ts
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-literals.ts
let firstName = "John";
let lastName = "Doe";
'Welcome ' + firstname + ' ' + lastName + '!';
`Welcome ${firstName} ${lastName}!`;
const-let.ts
var name = "John";
const name = "John";
var age = 30;
let age = 30;
// always use const unless you know the variable will be re-assigned
const name = "John";
name = "Jane"; // ❌ TypeError: Assignment to constant variable.
let age = 30;
age = 31; // ✅
objects-arrays.ts
const settings = new Object();
const settings = {};
const users = new Array();
const users = [];
arrow-functions.ts
// 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;
});

Try to avoid one character names unless it’s a loop, a counter or in a reducer.

one-character-variables.ts
// bad
const x = 'John Doe';
// good
foreach (let i in items) {
console.log(i);
}
//good
.reduce((a, b) => a + b, 0);
// bad
function q() {
// ...
}
// good
function query() {
// ...
}

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.

descriptive.ts
// bad
const update = () => {
// ...
}
// bad
const xyz = 'John Doe';
// good
const updateUser = () => {
// ...
}
// good
const fullName = 'John Doe';
index.ts
// bad
import foo from './foo.js';
import bar from './bar.jsx';
import baz from './baz/index.astro';
// good
import foo from './foo';
import bar from './bar';
import baz from './baz';

Use === and !== over == and !=

comparison-operators.ts
// bad
if (isValid === true) {
// ...
}
// good
if (isValid) {
// ...
}
// bad
if (name) {
// ...
}
// good
if (name !== '') {
// ...
}
// bad
if (collection.length) {
// ...
}
// good
if (collection.length > 0) {
// ...
}

// FIXME: to annotate a problem

fixme.ts
// FIXME: shouldn’t use a global here
total = 0;

// TODO: to annotates a solution to a problem

todo.ts
// TODO: total should be configurable by an options param
this.total = 0;