Member-only story

All JavaScript Variables Need to Obey These Fundamental Rules

Basic principles for valid JavaScript variable names

Mwiza Kumwenda
1 min readJul 15, 2024
Photo by Claudio Schwarz on Unsplash

Variables are the workhorses of JavaScript, holding the data that make your software tick — and they are everywhere.

Here are some fundamental rules that all valid JavaScript variable names should obey to avoid errors and for maintainable code.

  • A variable name should be one word, with no spaces.
  • Use alphabetical characters (a-z), numbers (0–9), and the underscore character (_). This is to avoid errors and for syntax compatibility.
  • Variables names can’t begin with a number otherwise you’ll get an error. This is because JavaScript uses numbers as a separate data type. For example, 1name is invalid, but firstName is okay.
  • Variable names are case-sensitive. For example, the variable names: myage, MyAge, myAge and MYAGE are four distinct variables. The key here is to be consistent in your naming/capitalization to avoid unintended behavior.
  • Don’t use reserved JavaScript keywords (such as else, function, if etc.) Because they have a special meaning within JavaScript.

Again, be consistent in your naming. The most widely adopted convention for variable names is camelCase. For example, firstName, lastName, and isLoggedIn etc.

--

--

Mwiza Kumwenda
Mwiza Kumwenda

No responses yet