camelCase and 2 Other Tips about JavaScript Variable Names

When it comes to JavaScript variable names, you have to keep in mind that JavaScript is like many other web programming languages–it’s picky about capitalization, spelling, and spaces. (And when I say picky, I mean PICKY.)

This doesn’t mean that you have to be a perfect wordsmith to write JavaScript code; you do, however, have to debug your code carefully, because one simple typo can cause your whole script not to run. Here are 3 common pitfalls:

Capitalization (Like camelCase)

Often, you’ll see examples of JavaScripts floating around on the Web with object and function names like “myObject” and “getPage.” These are both examples of camelCase, or the act of combining two words together and then capitalizing one or both words’ beginning letters. (This is also called Embedded Caps, nerdCaps, and a whole host of other terms, LOL!)

Since JavaScript is case sensitive, you have to be careful when you’re writing object and function names with CamelCase in mind. “MyObject” and “myObject” are treated as two different objects; “GetPage” and “getPage” are also treated as two different functions. Read over your code carefully and make sure all your variable capitalizations match!

Spelling (Yep, It’s Still Important)

Along with the issue of capitalization, the spelling of your JavaScript objects and functions matters, too. If you spell your function as “myAwesomeFunction” in one part of your script, for instance, and then misspell it as “myAwseomeFunction” elsewhere, then JavaScript treats those as two separate functions, and you likely have a non-working script.

You wouldn’t believe how many times a careless spelling mistake has thrown my coding off. (One tip: if you’re having trouble spelling the name of the function or object, consider either changing the name to an easier-to-spell option, or setting aside the hard-to-spell name in a little text file and copy-pasting it every time it comes up in a script you’re writing.)

Spaces in the Variable Name: Just Don’t

One reason so many JavaScript developers use camelCase or other forms of combined-word variable names is because JavaScript does not like for variable names to have spaces in them. Thus, if you have a multi-word function or object name, you combine the words, but keep the capitalized letters to make it easier to read.

Sometimes spaces can crop up if there’s an accidental line return in the middle of your file; resizing your script file’s window to check for these line returns could possibly help you debug a script that just won’t run! (This trick saved me some hair-tearing when I was a webdesign newb trying to get a script to work…I had NO idea what was wrong until I maximized the window and saw the sneaky little space hiding in one of the function names!)

Further Reading

W3Schools: JavaScript Statements
W3Schools: JavaScript Object Intro

Leave a Reply

Your email address will not be published. Required fields are marked *