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.
var keyword whereas the other is to use the
For now, and most part of this course, we'll concern ourselves with the former i.e.
let keyword, introduced with ECMAScript 6, is a way to create block-scoped variables. We'll explore
Alright, let's start by reviewing the syntax to create a variable using
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
y holding the values
var x = 10; var y = 20;
Working with these variables is just working with the numbers
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
y created before:
var x = 10; var y = 20; console.log(x); console.log(y); console.log(x + y); console.log(50 * x * y);
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!');
str holds a string value. It's concatenated with the string
' World!' and then the result logged.
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)
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
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."; console.log(text);
Variations of using
As we saw above, there isn't just one fixed syntax for defining a variable using
Let's see what this means.
Suppose we want to create three variables
z holding the values
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
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.
Here's the syntax for just the declaration:
When this statement executes, the given variable comes into existence as before. However, its value is
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
var x; x = 10;
Semantically, this is the same as
var x = 10;.
Let's consider another example.
Suppose we want to declare three variables
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.
- Names can't begin with a digit. Hence,
- Names can only contain alphanumeric characters (a-z, A-Z, 0-9) and the
$(dollar sign) characters; nothing else. Hence,
first-nameis invalid since it contains a hyphen (
-) which is illegal to put in a variable name.
- Names can't contain spaces. Hence,
first wordis invalid.
Tips for naming variables
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
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
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
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'.
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:
- PascalCasing: every word's first character is uppercased. C# uses Pascal casing for almost all identifiers. Some examples from C# are as follows:
- 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:
- SCREAMING_SNAKE_CASING: every word is uppercased and separated from the other using the
Coming back to our example, the variable
questionsasked could be renamed to one of the following:
questionsAskedin camel casing.
QuestionsAskedin Pascal casing.
questions_askedin snake casing.
QUESTIONS_ASKEDin 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?
The two most common conventions used for naming variables in most of the programming languages out there are camel casing and snake casing.
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!
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:
- Experience — the more you code, the better you become at naming.
- 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
For instance, consider the code below:
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
typeofoperator basically returns the type of a given value.
Here's its syntax:
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 (
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
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.
false. In the code below, we create two Boolean variables:
var isRaining = false; var authenticated = true;
For example, consider the code below:
var x = 10; console.log(typeof x !== 'undefined'); console.log(typeof y !== 'undefined');
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
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
Moving on, one extremely important thing to keep in mind while performing such a variable existence check is that
'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');
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.
This is formally known as 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
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'; console.log(str); 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'; console.log(str);
This is due to the effect of
str's declaration hoisted before running any other code.
For example, consider the following code:
var str = "Hoisting"; console.log(str + ' ' + str2); var str2 = 'is great!';
Only the declaration of
str2 (in line 5) over here is hoisted, not the assignment.
Likewise, before executing the
str2 has the value
undefined, which gets converted to the string
'undefined' when concatenated with
str + ' ' on line 3.