So far in this course, we have learned:
- How to select a web browser for JavaScript development
- How to install Node.js and npm, the Node package manager
- How to select a text editor (I use VS Code)
- How to run JavaScript both in your browser or from an HTML or JavaScript file
- Some general guidelines on JavaScript syntax
These are all important skills, but we still have not written our first line of JavaScript code!
That changes with this lesson. In this tutorial, you'll learn how to write JavaScript variables and statements, which are the building blocks of software engineering with JavaScript.
What Are JavaScript Variables?
In computer programming, variables are names that store a specified value.
There are three keywords that can be used to create JavaScript variables:
var
let
const
We'll explore each keyword in detail in this tutorial. First, let's talk about some restrictions on variable names.
The JavaScript var
Keyword
The var
keyword is one way of creating variables in JavaScript. For example, you can create a variable named first
with a value of Nick
with the following command:
var first = 'Nick';
Once this variable has been created, you can print its value to the console of your web browser with the following JavaScript statement:
console.log(first)
The output of this statement will be:
Nick
The JavaScript let
Keyword
The let
keyword is another way to declare a variable in JavaScript. As an example, you could create a variable named age
with a value of 24
with the following JavaScript statement:
let age = 24;
Once again, we can print the value held within age
to the console with the console.log
statement like this:
console.log(age);
Here is the output of this command:
24
The JavaScript const
Keyword
The JavaScript const
keyword is the third (and last) way to declare variables in JavaScript.
Let's create a variable called last
with a value of McCullum
using the const
keyword:
const last = 'McCullum';
As before, we can print the value of last
to the console with the console.log
statement like this:
console.log(last);
Here is the output of this statement:
McCullum
Variables declared with the var
, let
, and const
keywords have different characteristics. We will discuss these attributes in the next section of this lesson.
The Differences Between the var
, let
, and const
Keywords in JavaScript
The var
, let
, and const
keywords each behave differently, and understanding the differences in their behavior is an important step in becoming a mature JavaScript developer.
To start, the var
and let
keywords can be updated. The const
keyword cannot.
Let's consider an example:
//initial variable declaration and assignment
var first = "Nick"
let last = "McCullum"
const age = 24
//update the "first" and "last" variables
first = "Warren"
last = "Buffett"
//log the "first" and "last" variables to the console
console.log(first)
console.log(last)
Notice that the var
and let
keywords only need to be used the first time a variable is created. If you attempt to modify the variables at a later date using those keywords, your JavaScript code will return an error. Said differently, you do not need to use the var
or let
keywords when updating a variable's value.
What do you think happens when we attempt to run this code?
If you guessed that the new values of first
and last
will be printed to the console, then you are correct! Specifically, here's what the output would be:
Warren
Buffett
What happens if you try and update the variable that was created with the const
keyword? JavaScript will return an error.
As an example, let's try and update the age
variable:
age = 89;
This code returns the following error:
Uncaught TypeError: Assignment to constant variable.
at <anonymous>:1:5
The second important difference between var
, let
, and const
is a concept called scoping. Scoping refers to where a variable can be accessed within a JavaScript application.
We will have an entire section of this course that dives into JavaScript scoping in greater detail. For now, it is enough to remember that var
variables are scoped differently than let
and const
variables. var
variables are function scoped while let
and const
are block scoped.
One last note on the var
, let
, and const
variables - specifically regarding their history. var
variables have been around since JavaScript's invention in 1995, while let
and const
variables were introduced in ES6, which was a new version of JavaScript that rolled out in 2015.
If this is a lot to digest, do not worry! We'll learn more about this later. We will learn much more about variable scope later in this course.
JavaScript Variables and Strict Mode
If you play around with variables enough in JavaScript, you may notice that it is indeed possible to declare a variable without the var
, let
, or const
keywords. As an example, the following code runs successfully:
variable = 'This is my variable!';
You can then print this variable's value with a console.log statement like this:
console.log(variable);
Which returns:
This is my variable!
What is going on here?
Well, in JavaScript's early days, the var
, let
, and const
keywords were not as formalized as they are today, so if you're missing these keywords then the browser will automatically make the variable of type var
.
If you start a segment of JavaScript code with 'use strict';
, it disables this functionality. As an example, the following code returns an error:
'use strict';
variable = 'This is my variable!';
Here is the specific error that is returned by this code:
VM247:3 Uncaught ReferenceError: variable is not defined
at <anonymous>:3:10
Strict mode is useful in JavaScript development. Importantly, it is enforced by default when you use JavaScript modules (we'll learn more about that later). You will probably be writing most of your code using JavaScript modules, so you will not need to include 'use strict';
at the start of each of your JavaScript programs.
When to Use the var
, let
, and const
Keywords in JavaScript
One concept that beginner JavaScript developers sometimes struggle with is the choice of when to use the var
, let
, and const
keywords.
The truth is, there is no hard and fast rule. I do recognize that having some guidelines is helpful nonetheless, so here is what I do:
- When declaring a new variable, I use the
const
variable by default - If it turns out that I need to change the value of that variable later in my JavaScript program, then I will change the variable type to
let
- There are a few special situations where I may use
var
, but these are few and far between
I reiterate that these are not rules, but simply my opinion.
JavaScript Variable Naming Conventions
To wrap up this lesson, let's learn what the best practices are for naming JavaScript variables.
To start, JavaScript variables should generally not contain any special characters like !
, ?
, or "
. There are two exceptions to this. Both $
and _
are permitted to be use in JavaScript variable names.
The other aspect of JavaScript variable naming that you should keep in mind is the concept of camelCase
. camelCase
is a naming convention in which you start your first word with a lowercase letter, use no spaces, and uppercase the first letter of every word from the second word onwards.
Here are a few examples of camelCase
variable names to help you understand this better:
myFullName = 'Nick McCullum';
theNameOfThisCourse = 'JavaScript Fundamentals';
thisWebsiteURL = 'www.nickmccullum.com';
While there are other naming conventions (like snake_case
, which is more common in Python development), you will find that the majority of JavaScript developers use camelCase
when naming their variables in their applications.
Undefined Variables in JavaScript
You might be wondering what happens if we create variables but do not assign any value to them. For example, what happens when we attempt to run the following code:
let variable;
console.log(variable);
JavaScript has a built-in data type called undefined
to help handle this. As you'd expect, that's exactly what the output of tha last code block is:
undefined
The semantics here are a bit hard to understand, but a variable with value undefined
is different than a variable that has not yet been created.
To see this concept in action, try and print a variable in the JavaScript console that you haven't created yet. You will get the following error:
VM371:1 Uncaught ReferenceError: notAVariable is not defined
at <anonymous>:1:13
JavaScript also has a second data value to explicitly deal with a variable that is meant to explicitly state that it has no value. This value is null
.
Unlike the undefined
value, a value of null
must be explicitly assigned to a JavaScript variable like this:
const nullVariable = null;
You might be wondering why JavaScript has two different keywords to deal with undefined
or null
values. This is because the null
keyword can be explicitly used to change the value of a keyword that already exists, like this:
let name = 'Nicholas';
name = null;
console.log(name);
//Prints null
Final Thoughts
In this lesson, you learned how to write JavaScript variables and statements. Over the next few lessons, we'll be diving into each of the major data types in the JavaScript programming language.