Understanding variables in Javascript

Understanding variables in Javascript

Introduction to Variables.

Variables are not something unique to Javascript programming language only. Indeed, every programming language has the concept of variable. That’s simply because variable allow to process and store data very simply. But what is a variable exactly?

To answer this question, we can start with a use case. In coding, like in math, you process data and obtain some results. In both cases, the processing is deterministic, so the same initial values will always result in the same results.

Take a look to the following example.

2 * 5 + 3

This mathematical operation always equals 13, no matter what. So why should we execute this calculation every time? We could just write the result, and save some time. However, take a look at the following tweak:

2 * x + 3

Now, we have no predefined results for this calculation. In fact, the final result will vary depending on the actual value of x. If x is equal to 5, then we will result in 13, just like before. However, if x is equal to, say, 3, we will result in 9. In this example, x is a variable.

With variables, you can start to unleash the full potential of JavaScript. In fact, they are the main item that allows your code to work dynamically. With them, your code can do different things in different circumstances. In other words, you absolutely need variables.

Variables are placeholders. You can picture them as boxes that contain a value. In reference to javascript, Variables are used to store data, like string of text, numbers, etc. The data or value stored in the variables can be set, updated, and retrieved whenever needed. In general, variables are symbolic names for values. You can then reference to placeholder – the box – in any part of the code.

Declaring variables.

Variables can be declared with the var keyword, whereas the assignment operator = is used to assign a value (strings, numbers, booleans, undefined and null) to a variable. for example:

var  name = "Isaac Newton"; // strings
var  age = 17; // numbers
var  isMarried = false; // booleans
var  college; // undefined

In the above example we have created four variables, first one we assigned a string value to it, the second one we assigned a number value to it, the third one we assigned a boolean value to it, whereas the last one assigned we assigned a boolean value to it.

Declaring Multiple Variables at Once

In addition, you can also declare multiple variables and set their initial values in a single statement. Each variable are separated by commas, as demonstrated in the following example:

// Declaring multiple Variables
var name = "Isaac Newton", age = 19, isMarried = false, college;

/* Longer declarations can be written to span
multiple lines to improve the readability */
var name = "Isaac Newton",
age = 19,
isMarried = false,
college;

Note: A variable name can not be declare twice. In other words, the name of a variable must be unique. If two boxes have the same name how is JavaScript supposed to know which of the two to open?

Naming Conventions for JavaScript Variables

You can use pretty much any name you want for a variable. However, there are some basic (and common-sense) rules that must followed. To start, you can only use letters, numbers, and underscores. Obviously you cannot use spaces, quotes, hyphens, or any other type of special characters.

In addition to that, the very first character of a variable should not be a number. However, any other character can. Take a look at the following examples of good names vs bad names.

These names are valid.

myVariable
my1stVariable
_1
_variable
VARIABLE
Variable123
Variable_Variable
variable_1_Var

These names are invalid.

1stVariable
My Variable
My-Variable
MyVariable*
Var?

Another thing you want to consider is casing, which is how to combine lowercase and uppercase letters. This is crucial when your variable name contains multiple words (for example myVariable is My and Variable).

With camel case, each letter should be written in lowercase but the first letter of each word should be written in uppercase(e.g. thisIsACamelCasedVariable). You should use this casing in JavaScript!

Pascal case is similar to camel case, but the first word letter should also be in uppercase(e.g. ThisIsAPascalCasedVariable).

Snake case uses underscores to separate words, and it is all lowercase (e.g. this_is_a_snake_cased_variable).

Kebab case, instead, uses hyphens to separate words (e.g. this-is-a-kebab-cased-variable). However, as hyphens are not valid as part of variable names in JavaScript, this is not available to use.

The best practice tell us to use camel case. Even more important than that, you should be consistent. Always use the same style through all your files in your project, so that the code remains clear.

Reading and Debugging Variables

As we know, whenever we use the name of a variable in a formula, we are reading from it. So, take a look at the following example.

var b = a + 1;

In this example, we are reading the value of a, while assigning a new value to b. As you can see, in a single line you can do one assignment and one reading (and potentially more than one reading).

However, what if we want to actually see the content of a variable? That is useful when we are trying to understand if our code is working properly or not. We know that with alert() we can generate an annoying popup, but that’s not the best option in most cases.

Instead, we can use console.log(). This will basically generate a log in the console, a particular part of the Developers Tools on your browser.

var variable = "This is the console";
console.log(variable);

To open the console on your browser, right-click on any part of the web page and select Inspect Element (if you are on Firefox), or Inspect (if you are on Chrome). Alternatively, in any browser, you can press F12 on your keyboard. Then Look for the Console tab.

More on Variables’ Naming

We know that we should follow the camel casing. However, just picking the right case is not enough to create variables in the proper way. You should follow some rules to make your code clearer: Self-explanatory names – the name of the variable must tell what it contains (bad name: a, good name: username).

Broader Scope Larger name – if you use a variable only inside a code block, and you can see all the places where you use it with one glance, then it’s fine going with a short name. However, if your variable appears all over the place, be generous with its name. Do not sacrifice words (bad name: cnt, good name: wishlistProductCount). Instead, for smaller scopes, a short name is more than welcomed (in that case, cnt would be preferred). Use verbs when needed – mostly in variables representing a status (e.g. isActive, isLoggedIn, hasAuthorization).

Remember, computers will just process the code. Humans will read it (yourself included). You should write code for humans to understand, not for computers. And even if you think nobody will ever touch it again, you will – and you will forget for sure. And even if you think you won’t, eventually you will. So do yourself a favor, and write good and clean code by following those rules.

Conclusion

Variables are a crucial pillar of Javascript and of any programming language. With this article, you know what they are and how to use them effectively. You have now everything you need to start tackling dynamic behaviors in Javascript and customize what happens on your pages.