In the previous JavaScript Basics chapter, we learnt a little bit about variables in the language. Now we shall take in from there and explore many of common concepts associated with variables in JavaScript and programming, in general.

Specifically, we'll see how the var keyword works, the different ways to define variables using var and the idea of variable declaration. Not only this but we'll also see the rules for naming variables and how to come up with effective and meaningful names.

Lastly, we'll end with a discussion on the dynamically-typed nature of JavaScript before understanding how to check for a given variable's existence using typeof.

Let's begin.

Creating variables in JavaScript

To create a variable in JavaScript, we have mainly two options: one is to use the var keyword whereas the other is to use the let keyword.

For now, and most part of this course, we'll concern ourselves with the former i.e. var.

The let keyword, introduced with ECMAScript 6, is a way to create block-scoped variables. We'll explore let in the JavaScript Scoping chapter.

Alright, let's start by reviewing the syntax to create a variable using var:

var variable_name = value;

variable_name is the name of the variable whereas value is the value to assign to it.

The first part in this statement, i.e. var variable_name, is usually known as the variable's declaration. It serves to introduce a new identifier into the execution environment.

The second part, i.e. variable_name = value, is usually known as the variable's initialization. As the name suggests, it serves to set the variable to an initial (starting) value right after declaration.

In the code below, we define two variables x and y holding the values 10 and 20, respectively.

var x = 10;
var y = 20;

Working with these variables is just working with the numbers 10 and 20 directly. That is, we can add them, multiply them, log them, assign them to other variables, and so on and so forth.

Following, we experiment around with the variables x and y created before:

var x = 10;
var y = 20;


console.log(x + y);
console.log(50 * x * y);
10 20 30 10000


To state it once more, a variable can be used in almost every single way we can use the value that it holds.

Shown below is yet another example to confirm this:

var str = 'Hello';
console.log(str + ' World!');

The variable str holds a string value. It's concatenated with the string ' World!' and then the result logged.

Hello World!

Moving on, as the word 'variable' implies, we can change the value stored inside a variable to anything else at any point in a program. This is done by assigning a value to the variable.

Consider the code below:

var x = 10;
console.log(2 ** x);

x = 5;
console.log(2 ** x)
1024 32

First, x is equal to 10 and so the expression 2 ** x becomes 2 ** 10 which evaluates to 1024. Next up, x is changed to 5, and likewise the expression 2 ** x becomes 2 ** 5 which evaluates to 32.

This illustrates how we could change the value of a variable at any point in a program. And before the next assignment of a variable, it continues to use the value assigned to it before.

Alright, it's time for a quick task.

Write a piece of code to accomplish the following.

Create a variable text holding the text shown below:

The ' character is called an apostrophe.

and then log the text to the console.

Since the given text contains a single quote (') character in it, we'll denote the string using a pair of double quotes (""):

var text = "The ' character is called an apostrophe.";
The ' character is called an apostrophe.

Variations of using var

As we saw above, there isn't just one fixed syntax for defining a variable using var in JavaScript. We can change it according to our need and preference.

Let's see what this means.

Suppose we want to create three variables x, y and z holding the values 10, 20 and 30, respectively.

The obvious way is to do this as follows:

var x = 10;
var y = 20;
var z = 30;

Notice each line over here. It's a separate var statement that ends at a semicolon (;).

Another way is to just use var once and then define all the individual variables one-by-one without having to write var again and again.

The same code above could also be expressed as follows:

var x = 10,
    y = 20,
    z = 30;

All the variable definitions are separated by commas (,). Note that there is no semicolon at the end of the first line, neither at the end of the second line. The semicolon is only appended to the third line, since it ends the whole statment which begins with var (in line 1).

Now which one these shall we use?

Well, it's totally a matter of preference.

We'll go with our old method of using a new var keyword for each variable definition. This is because we feel that it keeps the code readable and doesn't introduce any awkward indentation before all the subsequent variable definitions after the first one.

Furthermore, with using commas, there is always a chance to make a typo and use ; instead of ,. This can modify the meaning of the variable definition statement completely.

That is, the statement following ;, where a , was expected, would merely create a global variable even if we meant to create a local one. This problem arises because JavaScript doesn't flag an error in such a situation, unless we're in strict mode.

Strict mode will be explored later on in the JavaScript Strict Mode chapter.

Moving on, at this point you might be thinking that using commas to define multiple variables at once is not useful at all.

Well, clearly no.

It might not be very useful when we include assignments in the definitions, but if we are just wanting to declare multiple variables at once without any assignments whatsoever, then the comma syntax proves to be really concise.

Now before we can see it in action, we ought to understand about another variation of creating and assigning variables in JavaScript. That is, to first declare the variable and then assign it a value.

In JavaScript, it's possible to omit the assignment part from a variable definition statement. What we're left with then is just the declaration.

Here's the syntax for just the declaration:

var variable_name;

When this statement executes, the given variable comes into existence as before. However, its value is undefined which is JavaScript's way to signal the absence of a value from a given identifier.

To change the value of the variable, we can simply assign it the desired value later on.

For example, the code below declares x and then later on sets it to the value 10:

var x;
x = 10;

Semantically, this is the same as var x = 10;.

With a separate declaration, we get the benefit of being able to declare the variable in a different scope than the one in which the variable is assigned a value. We'll see this later on in the JavaScript Scoping chapter.

Let's consider another example.

Suppose we want to declare three variables x, y and z but not assign them any value at the moment.

Using this short syntax, we can simply declare them all at once by separating each variable with a comma (,). The code below demonstrates this:

var x, y, z;

Now compare this with:

var x;
var y;
var z;

Which one is more readable and concise?

Well, clearly the first one. This is the syntax we'll often use in our course when we declare multiple variables whose assignment isn't to be done immediately after the declaration.

Rules for naming variables

Almost all programming languages enforce certain rules on the programmer when naming variables. This is done to prevent one from creating names that could introduce ambiguity into the respective program.

JavaScript is no way behind — it has a couple of rules as well that govern variable naming. These rules are quite standard ones and used in many other programming languages as well.

The rules we must follow when naming variables in JavaScript are as follows:

  1. Names can't begin with a digit. Hence, 2nd is invalid.
  2. Names can only contain alphanumeric characters (a-z, A-Z, 0-9) and the _ (underscore) and $ (dollar sign) characters; nothing else. Hence, first-name is invalid since it contains a hyphen (-) which is illegal to put in a variable name.
  3. Names can't contain spaces. Hence, first word is invalid.

Tips for naming variables

In this section, we aim to discuss a handful of tips to consider when naming variables in JavaScript, including which casing convention to use in order to break long words.

Be descriptive

A variable's name shall clearly describe what it's meant to hold.

For instance, suppose that you have to store a user's name in a variable. It would be really bad if you name the variable a (or x or u for 'user', or any random character). The name a doesn't tell much about what's stored in the variable.

A much better name would be username, or uname.

Well frankly speaking, the latter, i.e. uname, is also not very descriptive and sometimes could be ambiguous — uname could also stand for 'universal name', 'unsatisfactory name', or maybe even 'unique name'.

Don't be overly descriptive

Creating descriptive variable names is desirable, but we have to make sure that we remain within the bounds of description. Even too much description can be problematic.

Suppose we want to create a variable that stores the first name of a user. Being exceptionally descriptive, we could name it thefirstnameofuser, although this would be more than the required amount of description.

A better name would be firstname.

We have to remain in between the scale of descriptiveness — not too little, and not too much.

Abbreviate long words

Sometimes, it's really helpful to abbreviate long words in a given name to short and simple words, given that the abbreviation seems sensible.

For example, the variable dbname could work well instead of databasename. Here, we've abbreviated 'database' to 'db'.

The abbreviation 'db' for 'database' is quite a common one out there.

But keep in mind that abbreviations don't always work well.

For instance, naming a variable that holds the name of an object's property as pname would be a complete mess. pname could mean 'property name' or 'panel name' or 'previous name'.

A much better name would be propname — with the word 'property' abbreviated down to 'prop'.

Use a casing convention to break words

When a variable's name contains more than one word, it's desirable to use some casing convention to be able to distinguish between them easily while reading the variable.

Let's say we have a variable questionsasked that holds the number of questions asked in a quiz program. Seeing this name doesn't rightaway tell us about the individual words in it. Does it?

We have to gaze at the name for a while before we realize that it says 'questions asked'.

Worse yet, in some words the name could even be misinterpreted by the reader. For example, what can you read in idenum? Did you read it as 'ide num' or as 'id enum' ?

Well, the variable meant 'id enum' for 'ID enumeration'.

So to solve such ambiguities and make long variable names readable, we ought to use casing conventions.

Some common casing conventions are as follows:

  1. camelCasing: every word's first letter is uppercased except for that of the first word. Camel casing is the casing used in JavaScript. Here are some identifier names from JavaScript: indexOf, getElementById, querySelectorAll.
  2. PascalCasing: every word's first character is uppercased. C# uses Pascal casing for almost all identifiers. Some examples from C# are as follows: WriteLine, ReadLine, GetType.
  3. snake_casing: every word is lowercased and separated from the other using the _ (underscore) character. PHP uses snake casing for most of its predefined functions. Some examples from PHP are as follows: array_push, mysqli_connect, str_split.
  4. SCREAMING_SNAKE_CASING: every word is uppercased and separated from the other using the _ (underscore) character. This casing is commonly used to denote constants in many programming languages, including JavaScript. Some examples are: MAX_VALUE, MAX_SAFE_INTEGER.
As we shall see later in this course, identifier names could not only describe the data they point to, but also to what the identifier itself is i.e. is it a class, a constant, a method and so on.

Coming back to our example, the variable questionsasked could be renamed to one of the following:

  1. questionsAsked in camel casing.
  2. QuestionsAsked in Pascal casing.
  3. questions_asked in snake casing.
  4. QUESTIONS_ASKED in screaming snake casing.

Now it doesn't require much effort on our side to distinguish between the different words used in the variable's name.

But which one of these should we use?

Which casing convention to use in JavaScript?

The two most common conventions used for naming variables in most of the programming languages out there are camel casing and snake casing.

The question of 'which convention to use in JavaScript' really boils down to the question of 'whether to use camel casing or snake casing in JavaScript'.

Honestly speaking, this is solely a matter of preference. If you like camel casing, go with it. Similarly, if snake casing appeals you, go with it. Whatever you choose, make sure to stick with it — consistency is a must!

In this course, we'll use the camel casing convention to name variables. The reason is extremely simply — it's the convention used throughout JavaScript for function and method names.

Long story short, naming isn't any scientific theory to learn — it's purely an art.

In your journey of programming, you'll be able to come up with extremely effective variable names with:

  1. Experience — the more you code, the better you become at naming.
  2. Lots of trial and error — keep on altering the name of the variable unless and until you think it communicates its purpose in the best way.

Checking for a variable's existence

When working in a dynamic language such as JavaScript, it's extremely useful to have the feature of checking whether a given variable really exists before we use it.

For instance, consider the code below:

Uncaught ReferenceError: x is not defined at <anonymous>:1:13

We log the variable x and get an error thrown back at us. It's simply because there isn't any definition of x anywhere in the code.

The way we check for the existence of a variable is via typeof.

The typeof operator basically returns the type of a given value.

Here's its syntax:

typeof value

value is the value whose type we ought to determine.

When provided with a non-existent variable, typeof returns the string 'undefined'. This return value can be used to determine whether a variable is accessible or not.

That is, we can compare the return value of typeof as applied on a non-existent variable with the string 'undefined' using the non-equality (!==) operator.

The non-equality operator, denoted as !==, compares two values together and determines whether they are not equal to one another. If the given values are not equal, it evaluates down to the Boolean value true, or else to false.

What is a Boolean?

A Boolean is a true or false value that's used most commonly in conditional programming — executing code based on given conditions.

The name 'Boolean' is in honour of the prolific English mathematician George Boole who's generally considered as the father of symbolic logic.

In JavaScript, the two literal Boolean values are true and false. In the code below, we create two Boolean variables:

var isRaining = false;
var authenticated = true;

As we shall see later in the JavaScript Conditions — Booleans chapter, these values are used in executing code conditionally.

For example, consider the code below:

var x = 10;
console.log(typeof x !== 'undefined');

console.log(typeof y !== 'undefined');
true false

Here we define a variable x and then check whether it exists or not by comparing typeof x with 'undefined' for equality. Since x exists, we get true output by the first log statement. However, since there is no such variable as y, the second log statement outputs false.

One thing to note here is that typeof deals with a non-existent variable specially. That is, in a normal expression, if we refer to a non-existent variable, JavaScript throws an error. However, in typeof, doing the same doesn't lead to any errors whatsoever. This is because the internal engine is configured to treat non-existent variables differently when used in a typeof expression.

Moving on, one extremely important thing to keep in mind while performing such a variable existence check is that typeof returns 'undefined' even for a variable that's declared but not assigned a value.

This can be seen as follows:

console.log(typeof x !== 'undefined');

var y;
console.log(typeof y !== 'undefined');
false false

For us, this means that if we get 'undefined' returned by typeof while inspecting a given variable, we can NOT be 100% sure that the variable doesn't exist.

However, at least we can safely assume that the variable isn't of use to us (either because it's non-existent or not assigned a value) and hence not proceed with consuming its value for any purpose in our program.

Enjoyed reading so far? 👌

Leave out a review for this chapter to us by sending a message to our Instagram page @codeguage.

Send message

Variable hoisting

Once JavaScript code is parsed and ready to be executed, first all of the variable declarations are put into action before executing any other statement in the code.

This is formally known as hoisting.

Executing all variable declaration statements before any other statement in JavaScript is referred to as variable hoisting.

In practice, hoisting just seems to bring all variable declaration statements to the top-most location of wherever they are defined.

In reality, however, there isn't anything such as 'bringing the variable declarations up' — it's just an analogy drawn to help the developer understand what essentially is happening.

Due to the effects of hoisting, a variable can be assigned a value in source code way long before it's actually declared via the var keyword.

Although no one would ever want to do this, it's a feature to be aware of so that we don't mistakenly write code that executes contrary to how we expect it to.

For instance, consider the following code:

str = 'Hoisting';

var str;

Despite the fact that we are assigning to the variable str in line 1 before it's actually declared in line 3, this code doesn't flag any errors whatsoever (even though it should've).

That's because during execution, it's the same as the following code:

var str;

str = 'Hoisting';

This is due to the effect of str's declaration hoisted before running any other code.

Keep in mind that JavaScript only hoists variable declarations, not the values assigned to the variables within the declaration statements.

For example, consider the following code:

var str = "Hoisting";

console.log(str + ' ' + str2);

var str2 = 'is great!';
Hoisting undefined

Only the declaration of str2 (in line 5) over here is hoisted, not the assignment.

Likewise, before executing the console.log() statement, str2 has the value undefined, which gets converted to the string 'undefined' when concatenated with str + ' ' on line 3.