Home

Naming JavaScript Variables

|
|  Updated:  
2016-03-26 7:38:18
JavaScript Essentials For Dummies
Explore Book
Buy On Amazon

A variable name should accurately identify your variable. When you create good variable names, your JavaScript code becomes easier to understand and easier to work with. Properly naming variables is really important! Here are rules JavaScript has for naming variables:

  • Variable names cannot contain spaces.

  • Variable names must begin with a letter, an underscore (_) or a dollar sign ($).

  • Variable names can only contain letters, numbers, underscores, or dollar signs.

  • Variable names are case-sensitive.

  • Certain words may not be used as variable names, because they have other meanings within JavaScript. Check out this complete list of the reserved words.

You’ll be faced with many decisions when choosing how to name your variables: Do you want to begin your variable names with an uppercase letter or a lowercase letter, or do you want to use camelCase? Do you want to use multiple words within your variable names? Do you want to use an underscore (_) between the words in your variable name? (Remember: Variables can’t contain spaces.)

Fortunately, you don’t have to make all these choices by yourself. Many professional programmers agree that there are best practices to keep in mind when naming your variables:

  • Don’t use names that are too short. Simple one-letter names or names that don’t make sense are not a good option when naming variables.

  • Use more than one word to name your variable. This will ensure your variable name is precise.

  • When using more than one word in your variable names, always put the adjective to the left. For example, this is correct: var greenGrass.

  • Pick a style for names with more than one word, and stick to it. The two most common ways to join words to create a name are camelCase and using an underscore (_). JavaScript is flexible — either method works.

No matter what naming format you choose, remembering and using the best practices and being consistent in your naming format will make your code better organized and help you on your way to becoming a professional JavaScript programmer.

About This Article

This article is from the book: 

About the book author:

Chris Minnick is an accomplished author, teacher, and programmer. Minnick authored or co-authored over 20 books, including titles in the For Dummies series. He has developed video courses for top online training platforms and he teaches programming and machine learning to professional developers at some of the largest global companies.

Eva Holland is an experienced web developer, tech trainer, and coauthor of Coding with JavaScript For Dummies. She is a co-founder of WatzThis?, a company focused on training and course development.