As with any program, JavaScript tells the computer what to do step-by-step. Your instructions are full of values. How do you talk about a value in your program? You assign it a name. With your value bound to a name, you can reference it in your program.
As in most programming languages, you bind a name to value with a what’s called variable statement. Generally speaking, variable statements have three items:
(1)KEYWORD (2)NAME = (3)VALUE
Here’s how the code may look in real life:
const learningTheBasics = true;
In the code above:
- “const” is the special function KEYWORD
- “learningTheBasics” is the variable NAME
- “true” is the VALUE
Let’s explore those one at a time.
Note: Prefer a video version of this article? View the video on my YouTube channel.
1. Variable keywords.
There are three different keywords used to declare a variable in JavaScript: var, let, or const.
Any keyword you choose will declare a variable, but they behave differently. Generally speaking, I use const by default, let when required, and var … never. Let’s ignore var for now because you shouldn’t likely be using it.
What’s the difference between const and let?
- const stands for “constant” and cannot be reassigned a different value (in other words, it’s a way of permanently assigning a name to a value)
- let can be reassigned a new value later in your program
By using const as the default, it ensures you don’t accidentally overwrite a reassignable variable (i.e., let). If you try to reassign const, your program will throw an error. If you meant to reassign it, you can change the keyword to let; and if you didn’t want to reassign it, it’s a good thing you used const. 😏
Note: I promised a brief explanation of var, so I’ll give that here. Var has been in the language since the beginning. It works just like the let keyword except that it is globally available anywhere in your JavaScript file. That may sound like a good thing, but it makes for a lot of bugs, as it’s easy to reassign a var variable unintentionally. Both const and let are block scoped, meaning you can limit how available they are to you in your code. If that doesn’t make sense, don’t worry. We’ll go over scoping later. For now, just use const by default and let if you need to reassign a variable (note: this is my preference and not a hard rule). One more thing: because var and let can be reassigned, some developers reserve the word “variable” for var and let. In that nomenclature, const isn’t a “variable,” but a “constant.” I usually call them all “variables” so if you hate that, learn how to write JavaScript and write a script that replaces “variable” for “constant” when applicable. 😉
2. Variable names.
The name is sometimes called the “identifier”; it’s what you use to speak about the variable later in your code. Before we get crazy, let’s start with some basic rules.
Variables cannot:
- start with a number
- be a reserved JavaScript word (there are certain words the JavaScript interpreter reserves)
- have a space between words
So these would all be invalid variable names:
const 1stLearner = 'me'; // “1stLearner” starts with a number
const var = 'variable'; // “var” is a reserved keyword
const my name = 'Chris'; // “my name” has a space
Variables must:
- begin with a letter (upper or lowercase), the dollar sign symbol ($), or the underscore symbol (_).
- only contain letters, numbers, underscores, or dollar signs
Best practices for naming variables
How should you name variables? Here are the generally-accepted best practices:
- Use “camelcase” to name variables. Camelcase means the variable name starts lowercase, but every additional word in the name starts with an uppercase letter. Because variable names are case-sensitive, the most important practice is to be consistent. Here’s an example without camelcase:
const listofnamesfromserver = ['jim', 'joe', 'pearl', 'pam']
Here’s the same example with camelcase:
const listOfNamesFromServer = ['jim', 'joe', 'pearl', 'pam']
Camelcase makes variable names easier to read.
Note: There’s one generally-accepted exception: true constants. If you follow my suggestion above (that you should use *const* by default), most of your variables will be *const* declarations, even though they don’t *have* to be constants in most instances. When people follow this practice, they usually fully CAPITALIZE variable names that *must* be constants for the program to work (e.g., you couldn’t change it to “let” without breaking your program).
- Optimization and speed is important, but so is upkeep and readability. While “x” is a fine name for a variable, it doesn’t tell you anything about what the variable points to and thus requires more work to understand. Later on, you can use tools to shorten and optimize your variables upon build. For now, be very descriptive.
Here are most of the reserved JavaScript words: as, async, await, break, case, catch, class, const, continue, debugger, default, delete, do, else, get, if, import, in, instanceof, let, new, null, of, return, set, static, super, switch, target, this, throw, true, try, typeof, var, void, while, with, yield, enum, implements, interface, package, private, protected, public.
3. Variable values.
Variables point to values and those values can be most any data type in JavaScript. The next lessons will explain data types, so for now, I’ll simply list the seven types:
- String: surrounded by “, ”, or ""
- Number: a number (either an integer or decimal point)
- Boolean: true or false (not surrounded by “, ”, or "" —> because that would be a string)
- Null: absence of a value
- Undefined: a special word meaning a variable or object is initialized but has no value
- Symbol: a special value that always returns a unique identifier
- Object: collections of data usually surrounded with { } (everything in JavaScript is technically an object)
Note: The assignment operator (i.e., how you assign the value to the variable) is a single equals sign. You can also update let or var variables with the equals sign as shown below.
How to Declare a Variable
To pull everything together, you declare a variable how we started:
(1)KEYWORD (2)NAME = (3)VALUE
There’s one more difference to note here between const and let:
- With const, you must provide a value
- With let, you can merely initialize it (e.g., “let firstName;”) and then provide a value later using only the name (because let can be updated later);
const firstName = 'Jenny'
This 👆 uses const, and must be assigned a value when you initialize it (e.g., you cannot merely type const firstName; because you can’t update a const variable later.).
let firstName;
firstName = 'Jenny'
This 👆 first initializes a let variable named firstName and then later updates the value by referencing only the name (e.g., firstName).