Importance of Variable declaration before use in Javascript

Subscribe to my newsletter and never miss my upcoming articles

I never really understood how important the basics/background/foundation of my development career is until I started missing or making simple errors that one would think are just trivial. These errors end up consuming a lot of time debugging because well, they don't prevent the program from running but just interfere with the accuracy of the results.

Perhaps I'll write an article on this in the future, about how developers especially new to the field rush to learn languages and follow tutorials that promise a full understanding of a language in 10 hours or a week and end up missing tiny yet crucial concepts in coding which become costly in their career - among them, Variable declaration.

Variables;

variables.png This is perhaps the most utilized word when learning any programming language. Every developer works with them throughout the day, code, and even your entire development career. The fact is we can't work or do any coding without them. So, today I decided to look at their importance other than the basic every developer is aware of - "holding memory spaces". I wanted to elaborate on the consequences of lousy variable declaration.

If you ask any developer the difference between a local and a global variable, they will have quite an easy time explaining it to you with something like;

Global variables are declared outside a function, can be accessed or used in any function within the program while local variables are declared inside a function and can be used only in that function.

They may even go further and elaborate the whole scenario using the term scope referring to where the variable is visible or accessible. This is all nice and educative but in reality, the practical part of this equation is a bit more complex than this. How? stick with me here. In both definitions of the global and local variables, there is a highlighted name; DECLARED. Declaration makes a huge difference between the two types of variables and in turn, the two types of variables define the accuracy or preciseness of any project.

Note here, I used precise and accuracy because, one may mess the rules of variable declaration and the program will still deliver results, but the issue would be whether the results in question are accurate or precise.

Now a syntax error one can use google,mdn,w3schools, and StackOverflow among other numerous sources to debug quite easily I might add, but when you have problems with variable declaration and scope, which remember is one of the first lessons every developer has to learn, then you are about to have a very difficult time because your programs will always run but the logic part will be No Bueno which is a huge problem because no client wants a product that works but delivers faulty results.

Enough of the literature let's have an example of how this would be problematic in a small program snippet. Now let's assume that you have a program that prints out a bunch of names in an array;

const list = function () {
  names = ["cyrus", "codes", "javascript"];
 console.log(names);
};

Note that the array has not been declared but if you call the function, in javascript the program runs just fine and indeed prints out the list of names, and not declaring doesn't seem to have any huge impact since it prints out the list anyway.

const list = function () {
  names = ["cyrus", "codes", "javascript"];
  console.log(names);
};
list();

Now, remember the list of names is in this case supposed to be a local variable only to be used and accessed within the function. I want you to go outside of the function and try to print out the list;

const list = function () {
  let names = ["cyrus", "codes", "javascript"];
};
list();
console.log(names);

and ALAS! We can access a variable that was just meant to be operated on within the function. Let me explain here. In javascript, any locally non-declared variable is treated as a global variable and the same applies in most languages. Now due to data manipulations in your code as you proceed this can be disastrous and since there are no errors here it becomes a huge problem trying to debug it. How to avoid this? let's declare our variable inside the function and see what happens;

const list = function () {
  let names = ["cyrus", "codes", "javascript"];
};

list();
console.log(names);

You'll get a very elaborate error basically indicating that the array names are not defined. The reason for this is a locally declared variable can only be used and accessed locally i.e within the function and like the code above shows, it is impossible to access the variable outside of the function as long as the declaration is done within the function.

If you want to print out the content of the function, declare the function, inside it declare the variables and print its content within the function or perform any other operation you want and then call the function outside to print out the content or give results of its operations.

Failure to declare variables may not be the only pitfall when it comes to the declaration. A function declaration can also be a huge issue if you are not cautious. Have a look at this example;

list = function () {
  // declare function/local variables
  let names = ["cyrus", "codes", "javascript"];
  // print out or perform functional operations
  console.log(names);
};
// call the function
list();


list = function () {
  // declare function/local variables
  let names = ["hash", "node", "works"];
  // print out or perform functional operations
  console.log(names);
};
// call the function
list();

If you run the code, javascript may not produce any errors - why? non-declared functions that end up sharing the same name and in fact, your program will produce two different outputs of a function named list, and assuming you have hundreds of lists then you'll have one heck of a time trying to sort them out.

[ 'cyrus', 'codes', 'javascript' ]
[ 'hash', 'node', 'works' ]

If declared, javascript will not allow the use of the same function name twice, but you have to make this happen by PROPERLY DECLARING YOUR VARIABLES. as follows;

let listName1 = function () {
  // declare function/local variables
  let names = ["cyrus", "codes", "javascript"];
  // print out or perform functional operations
  console.log(names);
};
// call the function
listName1();

let listName2 = function () {
  // declare function/local variables
  let names = ["hash", "node", "works"];
  // print out or perform functional operations
  console.log(names);
};
// call the function
listName2();

Oh, and lastly pay attention to the variable names or any other declared item names because calling non-existent functions and variables isn't a huge leap and all it takes is a difference of one letter or underscore making username a totally different variable from userName or even user_name.

I have really enjoyed creating this article and although lengthy it's a good reminder of how important often overlooked javascript simple syntax can make you a better programmer and hopefully it helps you in your developer career as it has helped me. Share it on Twitter or if generous enough follow me on Twitter and you'll get more insightful content right from where this came from.

Comments (2)

Edidiong Asikpo's photo

I totally agree with the points you've raised here. I never really looked at it in this way.

Thanks for sharing.

cyrusCodes's photo

Thanks for the response. Very much appreciated.