JS - Best Practices (Naming convention)

Class name :

Class name should be : UpperCamelCase.

Bad :

class tagsinputcomponent extends React.Component

Correct :

class TagsInputComponent extends React.Component

Const name :

Const name should be : ALL_UPPER_CASE.

Correct :


GET_USERS_URL http://localhost:4000/users


GET_PHOTOS_URL http://localhost:4000/photos


PHOTO_UPLOAD_URL https://api.application.v1/photo/upload


IS_ADMIN = false

Variables name :

Variable name should be : lowerCamelCase.
Use intention-revealing names to make names searchable.
When you choose a name think to the future : review, enhance, refactor …
The code is a story then make your storyline easy to follow.

Bad :

let d
let elapsed
const ages = arr.map((i)=> i.age)
x1 fe2 xbqne
incrementerForMainLoopWhichSpansFromTenToTwenty
createNewMemberIfAgeOverTwentyOneAndMoonIsFull
isOverEighteen()
const yyyymmdstr = moment().format('YYYY/MM/DD');

Correct :

let daysSinceModification
const agesOfUsers = users.map((user) => user.age)
isLegalAge()

 

Make meaningful distinctions and don't add extra, unnecessary nouns to the variable names, like its type :

Bad :

let nameString                    
let theUsers

Correct :

let name
let users

 

Make your variable names easy to pronounce, because for the human mind it takes less effort to process. Don't cause extra mental mapping with your names.

Explicit is better than implicit :

Bad :

incrementerForMainLoopWhichSpansFromTenToTwenty
let fName, lName
let cntr

let full = false
if (cart.size > 100) {
full = true
}

Correct :

let firstName, lastName
let counter
const MAX_CART_SIZE = 100
const isFull = cart.size > MAX_CART_SIZE

Functions name :

Functions name should be : lowerCamelCase.
A function name should be a verb or a verb phrase, and it needs to communicate its intent, as well as the order and intent of the arguments.
Function names should say what they do.
A long descriptive name is way better than a short, enigmatic name or a long descriptive comment.

Bad :

/**

 * Invite a new user with its email address

 * @param {String} user email address

 */

function inv (user) { /* implementation */ }


Correct :
function inviteUser (emailAddress) { /* implementation */ }

 

js best practices