Creation and use of variables in JavaScript

const post = "Lorem";

Publication date: 19-12-2021

Let start for the beginning... What is a variable 🤔

The most common definitions are of the type “they are a container of information” or “it is like a box in which you keep objects, where the box represents the variable and the objects inside the box are the value”. These definitions are not wrong, a variable IS a container of information, any type of information; at least in JavaScript, in other programming languages things change a bit.

The main reason that this container is called "variable" is because it is possible that it could change in time. ⌛

We see a common example in maths with the famous letter "X". The letter X is the variable and a value is assigned to it, the one that best suits at the time. In this case the number 9.

X = 9;

For luck to us, we are not limited to a single letter for naming variables. We can name them whatever we want! But you have to follow certain rules that will be clarified later. Keep reading. 😃

First you have to know what are the types of data or variables that JavaScript handles.

JavaScript variable types

  • Strings

It is the most common data of all. It is simply the union of text characters consecutively, spaces are also considered within this data type.

Strings must be enclosed in double quotes or single quotes. For example:

let stringExample = “Some text as a variable”;

Don't worry if you've never seen something like this before, the topic of declaring variables is clarified later, what is that "let" word and why the variable is written that way. Keep reading.👀

  • Numbers

As its name indicates, variables handle numeric data and it is the second most used data in programming.

let numberOne = 1;
let playerNumber = 10;
let dayHours = 24;

You can even assign negative numbers.

  • Booleans

It is the data that determines the flow of a program or app. It is only expressed in two ways: true and false.

let on = true;
let on = false;

To determine if a light bulb is working or not.

  • Null

It is the type of value that is assigned to a variable to say that it does not contain data.

A detail with this data type is that a variable declared without an assignment is not the same...

let volume;

…To one assigned with the value of null.

let volume = null;

In the first example the variable volume is declared and waiting for an assignment somewhere in the code. In the second example, it already has a value assigned but it is null, that is to say to the program directly that the variable volume has no value, like the currency of a declining third world country.

Do not confuse it with the value of 0 or Undefined.

  • Undefined

Undefined values are those that are waiting an assignment.

let secretsOfTheUniverse = undefined;

It is very rare to use undefined and null but it is good that you know that these types of data exist.

  • Symbol

WTF??? just prompt ("Enter your preferred deity here."); and Brendan Eich what is this for.

The data type mentioned above are known as primitive data type since they are what was used before version 6 of the language (ECMAScript6) came out. After this version, other data types such as objects and arrays were added but those are a somewhat more complex topic that will be explained later.😁

More details about variables in JavaScript

JavaScript is a weakly typed programming language. What does this mean?

Unlike other programming languages, variables can be assigned any type of data, it is not necessary to indicate whether it is going to be an integer (6), a floating number (0.6) or a string. It is simply declared and assigned.

Some consider it a disadvantage but it depends on the programmer.🤷‍♂️

There are some standards for declaring variables in this language. Let's see how this is.👀

How to declare variables in JavaScript

The declaration of variables is case sensitive. Is not the same

let glassOfWater = "water";

that

let GlassOfWater = "water";

Although both are called the same and have the same data, the language will consider them different variables just because the difference between letter G.

The second point is that the name of the variables must be descriptive. The more explicit the description, the better.

let first_pokemon = "Bulbasaur";

The third point is the way to declare variables, here I explain them:

JavaScript Variable Names

  • Camel case 🐪
  • It is the way to declare variables of compound names by placing a capital letter from the second word.

    let aRandomVariable = "Randomness";
  • Pascal case 🐫
  • It is the same as the previous example except that the first letter of the variable starts in uppercase.

    let ToolRules = true;
  • Under_score 🧛‍♀️
  • This way of declaring variables uses the underscore at the beginning of the name and to separate compound names.

    let _im_so_under_score = "xD";

    It is also valid not to declare the variable with the underscore at the beginning.

  • Dollar sign 🤑
  • This way declares variables using the $ sign at the beginning of the variable name.

    let $theNumberOfTheBeast = 666;🤘

Variable names cannot start with a number or another sign. At the time of printing they will give you an error and even your IDE can point out the declaration error.

If the reading got this far, a few lines above I wrote that would explain the word "let" before the variable name. The time has come with the next point. 😎

JavaScript var VS let

These two words are known as keywords and are used for the declaration of variables.

var variable1;
let variable2;

JavaScript variable scope. Differences between var, let and const

Before the release of ECMAScript6, only the var keyword existed for variable declaration. With this way of declaring you have to be careful because it has a global scope during the course of your program.

And what is global scope?

It is that the variable is going to be available in ANY part of the code.

You can call it and use it at any time within your program and that can be somewhat confusing and even dangerous because there may be value reassignment errors. And that is another peculiarity of the language, the variables are reassignable except for the constants.

If there is a global scope, there is also a local scope. True; 👍

Local scopes are determined by brackets within the program ({}).

📢 PAY ATTENTION!!

This is where the let keyword comes in. What differentiates it from var is that its local scope will not be affected if there is a variable with the same name outside of the code block.

For this kind of control it is preferable to declare variables with let instead of var.

To understand this point, it is preferable to graph it. 🙂

//What is enclosed within the white border is the global scope.
// At this point the variable can be used anywhere in the program.

var age = 17;
function showExample(){
var age = 23;
if (age > 18){
console.log("Can buy some alcohol.");
}
console.log(age);
}
/*What is inside the red border is the local scope of these lines of code. Notice the yellow brackets.*/

/*Don't worry if you don't understand something. For now just focus on the age variable and where it is located within the scope.*/
showExample();

In the previous example the age variable was declared twice, in the global scope with the value of 17 and in the local scope with the value of 23.

JavaScript will consider the last time the variable was declared and will reassign the age value from 17 to 23, so this person has forged her identity document and can buy alcohol.

Now the same example with let.

let age = 23;
function showExample(){
let age = 17;
if (age > 18){
console.log("Can buy some alcohol.");
}
console.log(age);
/*In this case the person cannot buy his precious beer because the age variable was not mutated by the declaration that is in the global scope. The age value in this scope is 17. */
}
mostrarEjemplo();

You can copy these codes into your IDE to check it but be careful with reassigning variables if you copy both.

The case for using const is when you want to use data that is immutable throughout your algorithm. As it can be an ID number or a name, unless you are the person in the previous example.

const pi = 3.1416;
const realBadAss = "John Wick";

If you liked this article, let me know through my social networks, also tell me if you think there was a missing detail to explain, if you didn't like it or if you want to buy me a coffee.😆