What is a variable?
Last updated: Oct 1
A variable is a way to reference data stored in memory in a human-readable way. Since this is a post about variables in JavaScript(JS)
, let’s use an example from that programming language.
const FIRST_NAME = “Marco”;
var age = 35;
let hobbies = ["violin", "photography", "cats"];
Variable syntax
Like anything else in programming, JS
has a syntax you must adhere to when using variables. declarationType uniqueVarName = value;
where declarationType
is var
, let
, or const
, uniqueVarName
is the unique variable name used and value
is a value that isn’t a reserved word.
Along with being a unique identifier in memory to access data, variable names in JS
are case-sensitive. This means that the computer views var name;
and var Name;
as two separate variables.
Speaking of, let’s discuss reserved words. This is a word that the designers of the programming language have reserved for a specific purpose. For example, var for;
isn’t a valid variable name, as for
is reserved for for
loops.
You can find the rules for naming variables in the Resources section. While each organization may have rules for naming variables, it’s a good idea (for yourself and your teammates) to use certain naming conventions. These will be discussed later, but for now, just write variable names that accurately describe the data they reference. and are easy for you and your teammates to understand.
Now that we took care of human needs, let’s understand the needs of the computer. Here’s the way the computer reads the syntax for the creation of a variable and its value:
Create data in memory
Make a human-readable reference to that data (point to that data). Remember, underneath the hood, the computer stores the data as bytes. Who wants to type all of that?
Point to that value in memory using the assignment
=
operator. This looks likevar
(orlet
orconst
)validVariableName = validValue;
. Don’t forget, that the value must be valid too. Otherwise, your code willthrow
anError
.
Variable data types
The data being referenced by any variable in JS
must be of any of the following data types:
String
A primitive data type, a string is anything in quotes.
JS
has support for ‘single’, “double”, or `backticks`.
Number
Whole integers(5), and floats (5.5) are supported.
Bigint
While technically an
object
,BigInt
is a unique data type that provides a way to represent very large whole numbers (larger than 2^53-1).
Boolean
true
orfalse
Undefined
The default value for variables that are declared (using
var
,let
,const
) but NOT explicitly assigned a value.
Null
A way of declaring that a variable has no value.
Null
is a value explicitly set by the Programmer.
Symbol
A way of assigning a unique ID to an object.
Object
A compound data type that stores data using
property:value
pair(s) inside curly brackets. Although, experienced developers know that under the hood, an Array is of typeobject
too.
Don’t worry if this doesn’t make sense to you just yet, it’s just meant to illustrate the acceptable JS
data types. When describing data types, you may have noticed I used the terms primitive and compound.
A primitive data type (like a boolean
, string
or number
) can only hold a singular value. A compound data type (like an array
or object
) can hold multiple values.
Naming conventions
Naming conventions are the rules you follow when describing (naming) data. They also discuss how to use whitespace, indentation, and comments. The rules can be anything from using certain words (according to the business logic), to using lowercase, uppercase, or a combination of both.
Using a naming convention(s) promotes code readability and maintainability. Here are the names and syntax of varying naming schemes in JavaScript
.
camelCase
One of the most common variable naming schemes for variables and functions
UpperCamelCase
Often used for Classes
UPPERCASE
Often used for constant variables.
snake_case
Another way to name a constant variable.
const bootcampsAreBad = true;
questionCase
Used for boolean values. This isn’t an official term, as far as I know. I just came up with it now!
var isSubscriber = true;
Var, let, const
As you’ve seen, there are three ways of declaring variables in JS
, let
, var
and const
. You may have heard that var
is outdated and to use let
or const
instead. At Perpetual Education(PE), we are taught the nuances between these different JS
keywords and how to use them thoughtfully.
Variables declared with const
(which is an abbreviation of constant ) cannot be redeclared, in contrast to let
and var
(allows redeclaration). But to fully understand the differences, you should have a basic understanding of scope.
Variable scope
Scope refers to the rules that determine where data is available. JS uses lexical scope: where the visibility of variables/functions are based on where they are declared. In the documentation, you’ll often hear of these three types of scope:
Function scope
A variable declared in the
function
scope is available from within thatfunction
only. Variables declared withvar
havefunction
scope. *note* : when usingvar
in afor
loop the counter (often namedi
) variable is available outside the loop.Due to the use of
var
and the resulting variable scope behavior, in this case, you can access and log the variablei
both inside and outside thefor
loop, despite the loop itself being declared in the global scope.Because variables declared with
var
are hoisted to the nearest function scope, or the global scope if they are declared outside of any function we can access the the variable outside of the code block. For example://global scope for (var i = 0; i <= 5; i++) { console.log(`i inside the loop: ${i}`); // i is 0,1,2,3,4,5 } console.log(`i outside the loop: ${i}`); // i is 6
Global scope
A variable declared in the global scope can be accessed from anywhere in the program. This is the top-level scope of your program outside of any
{}
(code block). Let’s examine a catobject
declared in global scope.// a cat object in global scope let cat = { name: "snuffy", cute: true, hobbies: ["eating", "being sassy", "piano"] } console.table(cat); // see the data in tabular format console.log(`${cat.name} the cat's first hobby is ${cat.hobbies[0]}`);
Block scope
A variable declared in the block scope can be accessed only within a code block
{}
(like afunction,
if
, orfor
loop). Variables declared withlet
andconst
are block scoped. Using a familiar example:
for (let j = 0; j <= 5; j++) {
console.log(`j inside the loop: ${j}`); // i is 0,1,2,3,4,5
}
console.log(`j outside the loop: ${j}`); // ReferenceError: j is not defined
Feel free to try the same example with const
, and you’ll get the same ReferenceError
.
Garbage collection
Remember earlier when I mentioned that computers/programs have data that are referenced by variable names? This data is stored in the computer’s memory. And like any resource, memory is finite.
This is where the concept of memory management, or garbage collection comes in. Unlike some languages with manual memory management (like C
), JS
automatically manages (allocates or releases) the memory. Without memory management, your program will consume all the resources and crash your application/slow down your computer.
In JS
, once a variable is not being used anymore (has no more references to it) it is garbage collected. After collection, it no longer exists (as far as the computer is concerned), and its place in memory should be released so other data can exist.