Variables

What is a variable?

A variable is a named representation of a value. A variable could represent numbers, strings, collections, functions/methods, etc… anything really.

How do you create a variable?

Different languages have different ways to create a variable. In all languages there are 2 parts to creating a variable.

  1. Declaration
  2. Definition

Declaration is basically stating that you want a variable, you want it to have a certain name, and possibly that you want the variable to be of a certain type.

JavaScript

// To get the results below open your browsers developer tools, 
// hit F12 on the keyboard. Then select the console and you 
// will be able to type the code below

// Declaration
var value;

Definition is where you assign a value to the variable. Depending on the language you are programming in, this is either done on the same line as the declaration or a separate line.

JavaScript

// Definition
value = 5;

// ex. Declaration and Definition on the same line
var pi = 3.14;

Why use a variable?

Having a variable allows you to provide a name for a commonly used value, for instance π. π is 3.14…, but we don’t have to know that if we can use a variable to represent it. Another usage of a variable is to track a result through the flow of the program. We could have a variable named “result” and at the start of the program that value is 0. As the program progresses the result could change to a 3 and then back to a 1 ending in a 5. If the program could be asked the current result at any point it would be convenient to have that value available in a variable. Lastly, it is the only way to accomplish certain operations. If you have a complex value and you want to know if another value is exactly the same the only way is to have both values in variables. If they weren’t then they would compare as different even if they had the same values in many cases.

JavaScript

// Variables can change value over time
var result = 0;
result = 1;
result = 5;
console.log(result);
5

// example of a complex value
var a = {};
var b = {};

// This comparison with out variables will not only not give a valid result, it will actually cause an error.
// {} === {}; // BOOM!
a === b;
false
a === a;
true

We’re Done

That is all there is to Variables for now. As Always, I hope you learned something from this, but if not please look at some of the other articles as they are more advanced and may lend you some insight in the world of software development.

Leave a Reply

Your email address will not be published. Required fields are marked *