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:
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.
The names can be comprised of letters and numbers, but they have to start with a letter.
Underscores â€œ_â€ are allowed, but not dashes â€œ-â€œ as they will be mistaken for minus signs or spaces.
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; 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.