JavaScript Basics Part 4: Variables

Variables offer a way to store values of strings, numbers, and boolean data types, as well as being able to reuse at any point within your script. Declaring or creating variables is a common practice when writing any sort of script or program. I will setup variables to store different bits of data that I want to access multiple times. They allow you to create cleaner, more readable, and more organized code.

There are two ways to use variables, the first is by just declaring a variable as show below:

var numClicks;

You can also declare a variable and set a value to it. The “var” syntax is used to declare the variable. You can also forego using the “var” text, and just set the variable to a value. Using the word “var” before declaring the variable is another way of keeping your scripts organized.

var numClicks = 12;
numClicks = 12;

In the second example above, I have also used an operator to assign a value to my variable. The assignment operator (=) is one of the more commonly used operators.

Variable rules and best practices
There are some important rules to follow when creating variable names.

Reserved Words
You cannot use any of JavaScript’s reserved words, which are used in the JavaScript language itself and using them would create a conflict.

Variable names
The names can be comprised of letters and numbers, but they have to start with a letter.

var mainBtn1;

Underscores “_” are allowed, but not dashes “-“ as they will be mistaken for minus signs or spaces.

var main_12453_bar;

Variable names are also case-sensitive, so the following four variable names will be interpreted as different variables, even though it’s the same letter, the case is different.

var mainBtn;
var Mainbtn;
var mainbtn;

A common practice among web designers and developers is to use camelCase. To create camelCase, you make the first letter of the first word lowercase, and the first letter of the second word upper case and no spaces are present.

I will often use camel Casing when creating variable names and/or creating function names. It’s a nice way to adhere to a standard that other developers can immediately recognize, and it also helps avoid long names. I find it much easier to copy and paste since its all one word. A downside to camel Casing is when creating really long variable names or functions that can become illegible.

var mySpecialComputerForDoingMoreThanOneThingProgram;

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: