DEV Community

WestonDease
WestonDease

Posted on

JavaScript Variables

Variables are everywhere in programming. It makes the process a bit like algebra in that you have an understanding that variables represent some data so you don't have to constantly reenter the same data over and over throughout the application. It also works to make values mutable across the app, allowing you to have a flow of logic that goes beyond hard coding answers into problems. Additionally variables allow you to make a minor change in the value at some point in the code and have it carry across the program. The key to maximizing the use of variables (and any part of programming or even perhaps life in general) comes down to understanding how they work. You must look under the hood and see how the engine works to fix the car.

There are few types of variables in JavaScript when compared to more basic languages like Java and C#. This doesn't however change what types of values can be stored in variables as it is still the conventional types of numbers, strings, booleans, and arrays (though they are objects and objects can also be thought of as variables).

Starting with the basics, lets declare variables. The most basic variable declaration in JavaScript is "var". This sets the scope of the variable to the execution context to the whatever its declared in. That means if it was declared in a function, it still has global scope. Using "let" then allows you to set block scope for a variable. The type "const" forces you to declare its value on declaration but it can still change if its an object.

Naming variables is more form than function. And by form I mean that whatever you name it has to be for the sake of you and others reading your code. Your names should establish in a quick few terms what the variable represents and perhaps what it is used for. Some conventions for naming is to use cammelCase for most variables and ALL_CAPS for constants.

Assignment of variables is done with the "=" operator with the variable on the left and a value on the right. Note that this is different than "==" which is a value comparison and will result in a true/false return value (also this ignore the data type as 4 == "4" will return true, 4 === "4" will not). Some quick assignment shortcuts include "+=" to add to the original variable, the same is true for "-=", "*=", and "/=" for their respective operations. When variables are first declared, unless given a value on declaration, will have the value of undefined.

Overall JavaScript is a smart language. So variables are going to be simple. But this doesn't diminish the subtlety of their implementation. I certainly didn't cover everything in this and the technicality gets even deeper. Perhaps I will comeback to this subject soon and bring a whole new bag of tricks to the table.

Top comments (0)