Naming Variables and Functions in JavaScript

Question
How should I name variables and functions in JavaScript?

Answer
You want to ensure that variables are camelCase and begin with nouns. Function and method names also need to be camelCase but begin with verbs.

Comments
Attempt to make variables as short as possible without sacrificing meaning. Try to name them according to their data type. For example, age is a number. You want to avoid meaningless names, and reserve single-character variables such as i and j for use in loops.

Examples

// Good names for variables.
var length = 12;
let firstName = "Jason";
let pageLoaded = false;

// Use can, has, and is verbs for functions that return booleans.
function canDownload() {
    ...
    return true;
}

function hasAccess() {
    ...
    return false;
}

function isAuthorized() {
    ...
    return true;
}

// Use get verb for functions that return non-boolean values.
function getAge() {
    return age;
}

// Use set verb for functions that save values.
function setLanguage(name) {
    ...
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s