Variables
Prefer const
Require const declarations for variables that are never reassigned after declared.
let a = 3
console.log(a)
const a = 3
console.log(a)
Use meaningful and pronounceable variable names
const yyyymmdstr = moment().format('YYYY/MM/DD')
const formatted_current_date = moment().format('YYYY/MM/DD')
Use searchable names
// What the heck is 86400000 for?
setTimeout(restart, 86400000)
// Declare them as capitalized named constants.
const milliseconds_per_day = 60 * 60 * 24 * 1000 //86400000
setTimeout(restart, milliseconds_per_day)
Use explanatory variables
const user_map: Map<string, User>
for (const key_value of user_map) {
// ...
}
const user_map: Map<string, User>
for (const [id, user] of user_map) {
// ...
}
Avoid Mental Mapping
const c = get_count()
const u = get_user()
const count = get_count()
const user = get_user()
Don’t add unneeded context
const Car = {
car_make: "Honda",
car_model: "Accord",
car_color: "Blue"
}
function paint_car(car: Car, color: string): void {
car.car_color = color
}
const Car = {
make: "Honda",
model: "Accord",
color: "Blue"
}
function paint_car(car: Car, color: string): void {
car.color = color
}
Use default parameters instead of short circuiting or conditionals
function load_pages(count?: number) {
const load_count = count ?? 10
// ...
}
function load_pages(count: number = 10) {
// ...
}
Use enum to document the intent
const GENRE = {
ROMANTIC: 'romantic',
DRAMA: 'drama',
COMEDY: 'comedy',
DOCUMENTARY: 'documentary',
}
enum genre {
romantic,
drama,
comedy,
documentary,
}