JavaScript: Variables

JavaScript: Variables

A one stop piece for all you need to understand the concept of variables in JavaScript.

A variable is like a box where we can store data or a reference to data. In this article, we are going to learn about how to create and use variables.

Let me attempt to describe what a variable is, using three different examples;

Example 1: When a child is born, he is named and throughout their life, he/she would be referred to by that name (unless the name gets changed at some point).

Everyone must have a name or a way by which they are referenced.

Have you seen anyone without a name? How were you able to call them?
In a perfect world, everyone should have a name or a unique way we can refer to them. In JavaScript, every variable has a name.

Example 2: In a maths equation when we say x = 1 we are saying, anywhere you see x, you should replace it with 1. In this case, x is a variable, while 1 is the value of it. That is, x points to 1.

In this case, without x, there will be no reference to 1. There could be other instances of 1 in the equation but those will be different than the 1 which x was referring to.

/* The code below means x is 1 
 * So during execution, anywhere x appears after the line below, 
 * the complier replace x with 1.
 */
let x = 1;
console.log(x); // This line will log 1 to the console.

Example 3: A variable is sometimes considered as a container for a type of value. If we adopt this idea, then its name would be what identifies the container, its value would be the content of the container and its type would be the type of the content in it.

A popular water brand here in Nigeria is known as "Eva". Let's say you bought Eva water, took it home and placed it amongst other water brands. You can easily say to someone "Please get me the Eva water over there" and because of the name, it becomes easy for the person to get you exactly what you need. It's all water inside the other bottles but you were specific that you need Eva so that's what you'll get.

This analogy is to let you know that the values are always referred to by the name of the variable. Even if the value is what gets used in the computation eventually.

In this case, the content of the bottle is water and the type of it is liquid.

// Add the line of code below to the previous code snippet to
// find out the data type of x;
console.log(typeof x)

Variables exist in our program to help us hold values and be able to refer to them whenever we need to. Anywhere a variable is mentioned, the value of that variable is what's being used for the computation at the time.

Variable Declaration

let score;

The program above declares/creates a variable called score.

In JavaScript, creating variables is that simple. The type of the variable is the type of the value stored in it. That is, if the variable score holds a value of 1, the type of the score variable is number. So we can say, score is a number variable.

To create a variable, we have to do the following;

  1. Declare the variable using either of the keywords let, const or var.

  2. Determine a name to call the variable and write it on the same line as the keyword used in step 1.

let score; // creates variable 'score'

Notice that this time, we do not give it a value. We just simply created a container which will store something but for now, it is empty. Although it has no content at the moment, we'll surely provide content for it.

Variable Assignment and Initialization

We assign a value to a variable by using the assignment (=) operator, the variable name to the left of it and the value to the right.

score = 1; // assigns 1 as the value of score (this is called variable assignment)

When we combine variable declaration and assignment in one operation, it is called variable initialization.

let score = 1; // Here we declare the variable score, and assign the value one to it

This simply means we provided an initial value for the variable when it was created.

Calling a Variable

At any time in our program, if we want to use the variable for any operation, we can simply just "call" it. To call a variable simply means to mention or use it.

console.log(score + 1) // 2

In the code snippet above, the variable score is used in the line of code therefore, It will be replaced with its actual value during the code execution. That means we'd have 1 + 1 executed, resulting to 2 being the result.

In the next article, we'll learn about different data types and how to work with them but first, let's learn some more about deciding what to call a variables and some rules that will guide us in doing so.

Variable Naming

Just like naming a human or pet or labelling an object, we always put in much thought to ensure the name tells a story and gives an idea of how we feel about the role of that pet, human or object. In africa, we are very intentional to ensure that names convey perceived purpose or function.

JavaScript is somewhat liberal when it comes to how variable naming can be done and also how long it could be.

For example, pneumonoultramicroscopicsilicovolcanoconiosis, is a valid variable name in JavaScript as long as it is.

It is generally a good practice to give meaningful names to variables and they should be of a reasonable length.

Let your variables be simple and contextual e.g., author, publishedDate, readTime, shouldCompress etc.

It should be self-explanatory. Just avoid cryptic names where possible.

Reserved Words

Even though we can create variables as we wish, some names are already being used within JavaScript to mean something specific. These names cannot be used by a developer to identify a variable. They are called reserved words.

For instance, the keyword catch is used to properly handle an error and prevent it from crashing an application. Hence, you cannot call a variable catch in your program.

Below are all the reserved words in JavaScript;

arguments await break case catch class const continue debugger default delete do else enum eval export extends false finally for function if implements import in Infinity instanceof interface let NaN new null package private protected public return static super switch this throw true try typeof undefined var void while with yield

NB: You do not need to memorize all these at all. If you try to use them, you'll get an error and you'll learn to recognize and know them with experience.

Also, JavaScript has some rules that you must follow when naming variables as well as generally accepted conventions (best practices) that you should know about. Let's talk about them in the next section.

Rules for naming Variables in JavaScript

  • Reserved words cannot be used as variable names.

  • The first letter of your variable name should be an alphabet, underscore (_) or a dollar sign ($). You cannot use a number as the first character of your variable name.

    Even if some other kinds of special characters are allowed to start a variable name; as a way of good practice and avoiding complexities at the start, you should just always start with a letter. Using an underscore or dollar sign is symbolic by convention and we'll learn what they mean in the future.

  • The rest of the variable name may contain anything but symbols, punctuations, and reserved characters (+, -, * etc).

  • Variable names are case-sensitive. This means Boy and boy will be treated as different variables in your program.

  • A variable name can be as long as is necessary for it to make sense. There is no limit imposed by the language.

  • Spaces are not allowed in variable names.

Popular Variable Naming Conventions

  • Variable names with multiple words should use camel casing i.e., the first word has to be all lowercase while the first letter of subsequent words should be uppercase e.g studentRegistrationNumber

  • Use uppercase letters for constant variables e.g const PI = 3.1432

  • If a constant variable is composed of multiple words, use snake casing (separation of words with an underscore) e.g const PROGRAM_NAME = "Vacation planner"

  • If a variable is meant to be private, prefix its name with an underscore e.g., let _memorySize = 2042.
    Note: This is just to let the team (others working on the project) know that the author intends to use it as private. It doesn't prevent the value of the variable from being accessed (there are other ways to ensure this).

  • It is common practice to prefix boolean variables with is or has e.g., let isMarked = true

Summary

Variables are "pointers" to values. When you mention (use) a variable anywhere in your code, what happens is that the variable identifier (name) is replaced with the value it points to. It's just like when you call someone's name. The name doesn't respond, the person (value) behind the name is what you hope to get as a response.

By way of retention, do not try to cram all these rules and conventions. Feel free to refer back to this article when programming and in a short amount of time, you'll be used to all of them and you wouldn't need to refer to any article ever again to name your variables properly.

If you should have anything in mind, remember to start variables with a lowercase letter, if the variable is made of multiple words, subsequent words should start with uppercase letters.

To create a variable, use the keyword let, const or var followed by the variable name. If you wish to initialize the variable, then on the same line before the semi-colon on the line, input the assignment operator and variable value after it.

i.e. let score; or let score = 3; (if you wish to initialize during declaration).

If you wish to use a variable, just mention its name and the value of it will be used during the execution of your code.

In the next article, let's work with variables a bit more and also learn about variable data types.

Do not forget to like this post if it was helpful (you can like it up to 10 times), drop your questions or share your thoughts in the comment section and also subscribe to my newsletter to get updates whenever I release a new episode (scroll down to find the subscribe box)**.