Site icon JavaScript Artisan

What is a JavaScript variable?

What is a variable in JavaScript? A simple enough question that seasoned programmers don’t give it a thought, and most tutorials take little, if any, time to explain it. Sure, they show you how to use variables, but what, exactly, is a variable?

A variable is made up of two parts: an identifier and a value. An identifier is literally just a name, and a value is any piece of information that you want to use in your program. Here’s a quick example:

let priceOfCoffee = 4;
// let means we're defining a variable
// priceOfCoffee is the identifier
// 4 is the value

In its simplest sense, a variable is a value assigned to an identifier. You use a variable so that you and other developers can reliably access the data it contains. The rules for naming a variable in JavaScript are a bit complex, but a good variable name concisely describes the information it points to and uses the following conventions:

  1. Starts with a $, _ or letter
  2. Cannot not contain spaces, punctuation or other symbols
  3. Uses “camel case” – capitalize the first letter of every word, except the first one
  4. Is not a reserved keyword// good variable name let secondsLeftUntilExpiration;// bad variable name let secs;

(if you’re curious or confused about variable naming, you can use Mathias Bynens’ validator)

What kind of information can a variable be?

In JavaScript there are lots of different types of information, but come in two main types: primitives and non-primitives.

Primitives

Primitives are basic information like text, numbers, booleans (a value that is either true or false), etc. The seven types of primitives in JavaScript are:

Non-Primitives

Non-primitives come in two flavors: functions and objects. (Technically functions are objects too, but we treat them separately here for clarity.)

Functions are pieces code that can be executed.

// define with the keyword 'function'
let doubleThisNumber = function(numberToDouble) {
  return numberToDouble * 2;
};

// run with prentheses ()
doubleThisNumber(5); // will return the value 10

// or pass the function somewhere to be run later, without parentheses ()
runSomeWhereElse(doubleThisNumber);

Objects are ways to structure data so it makes sense and is easy to access. They can hold any amount of any kind of data, including other objects.

Objects store data by name and reference the name to get the data

// defined with curly braces to indicate it's an object
let meals = {
	breakfast: 'eggs',
	lunch: 'sandwich',
	dinner: 'pizza'
};

meals.breakfast // this is how you refer to the String 'eggs'
meals.lunch // this is how you refer to the String 'sandwich'
meals.dinner // this is how you refer to the String 'pizza'

Also worth mentioning are arrays. Arrays are a special type of object that store information in order (rather than by name) and you reference the information by index number, with the first index always being number 0, not number 1

// defined using square brackets to indicate it's an array
let olympicMedals = [ 'Gold', 'Silver', 'Bronze' ];

olympicMedals[0] // this is how you refer to the String 'Gold'
olympicMedals[1] // ... 'Silver'
olympicMedals[2] // ... and 'Bronze'

What do you do with a Variable?

The operations you can do with a variable are simple: read from it, write to it (also called “assignment”), or pass it along. Passing a variable into a function is essentially assigning it to another variable name inside the function.

// read from height, width and depth, multiply them, and write the product to volume
let volume = height * width * depth;

// assign it to another variable (read from one variable and write to another)
let originalVolume = volume;

// or pass volume along to be read inside the fillContainer function
fillContainer(volume);

An Important Difference

Variables that point to primitive values and non-primitive values are treated almost the same, with one important difference. Objects are mutable, which means you can change them and your variable will continute to point to the same object in its updated state. Primitive values are immutable, which means when you do any operations to a variable containing a primitive, your variable will point to a brand new value, not a changed version of the same value. So what on earth is the difference? This only matters when you have multiple variables pointing to the same value.

When multiple variables point to the same object and that object is changed, all of the variables will reflect the updated version of the object. Think of this like several people sharing a notebook. Any of them can add things, erase things, etc. No matter how the contents of the notebook change, it’s still always the same notebook, and whoever looks in it will see the most up-to-date version.

On the other hand, when multiple variables point to the same primitive value and one of them is updated, only that variable points to the new value. The other ones still point to the previous primitive value. Think of this like writing a check (who does that anymore, anyway?). If you want to change the amount (value) of the check, you can’t erase and rewrite anything on the check. You have to write a brand new one.

// primitives are immutable
let firstString = 'Violin';
let secondString = firstString;
// both reference the same string 'Violin'
secondString = 'Viola';
// secondString now points to a new string, 'Viola'
// firstString is still 'Violin'

// non-primitives are mutable
let firstObject = { unique: true };
let secondObject = firstObject;
// both reference the same object
secondObject.unique = false;
// firstObject.unique is now false also, because the object was mutated

// also watch out for passing object into or out of functions
markObjectAsUnique(secondObject); // imagine this function changes secondObject.unique to true
// now firstObject.unique is back to true

There is a lot more to learn about variables, data, and how to use them. Understanding the basics of what a variable is will help you build an accurate mental model of how they are handled by the JavaScript engine. With additional reading and practice, variable handling will become second nature as you grow and mature as a coder. Best wishes and happy coding!

Exit mobile version