Internal variables
So far we declared variables just outside of any function. Nobody prevents us from doing so from within of them, and now we'll learn why it's useful.
Keeping count of things
We want to give our users some feedback about their profile information, and tell them what they can improve. To keep things simple let's take in consideration just three properties: name, age and email, that can all be or not he there.
We have to display a message like 0/3, 2/3, 3/3.
Let's draft the function signature and some test calls:
function checkProfileProgress(user) {
// work in progress
}
const myUser = {
name: 'Jane Doe',
email: 'jane@doe.com',
age: 35
};
const mysteriousUser = {
name: 'John Doe'
};
checkProfileProgress(myUser);
checkProfileProgress(mysteriousUser);
In real life we keep track of quantities with fingers or by ticking lines on paper. Both methods have in common the concept of updating something. So far we have declared variables that didn't need to be updated, that why they are introduced by the const keyword.
There is another keyword that allows us to overwrite the contents of a variable: it's called let:
const user = { name: 'John Doe' }; let count = 0; if (user.name) { count = count + 1; } console.log('Count:', count);
Toggle Console Output
- Count: 1
The initial value of count is 0. The condition of the if statement is satisfied and its block is executed. The only instruction contained overwrites count with one plus whatever it has at the moment, count = count + 1. The log statement at the end reflects the updated value of the count variable, that is now 1. Now we can use this inside our function!
The increment and decrement operators
An expression like count = count + 1; is absolutely fine and easy to understand. In programming it's more idiomatic to use the increment operator (++). It's an unary operator that is written after the variable you want to increment by one (and by one only!):
let count = 0; // it's exactly like writing 'count = count + 1' count++; console.log(count);
Toggle Console Output
- 1
There is the decrement operator too:
let count = 1; // it's exactly like writing 'count = count - 1' count--; console.log(count);
Toggle Console Output
- 0
Both operators actually work even if prepended to the variable, but they have a different behavior that we don't want to discuss now.
We'll use the increment operator to make things more idiomatic. If you prefer the explicit notation feel free to use it in your personal code for now.
function checkProfileProgress(user) { let count = 0; if (user.name) { // like count = count + 1; count++; } if (user.age) { count++; } if (user.email) { count++; } console.log(`${count}/3`); } const myUser = { name: 'Jane Doe', email: 'jane@doe.com', age: 35 }; const mysteriousUser = { name: 'John Doe' }; checkProfileProgress(myUser); checkProfileProgress(mysteriousUser);
Toggle Console Output
- 3/3
- 1/3
Great! We are checking the properties one by one, and if they have found we update the count accordingly.
Declaration, assignation, initialization
Now that we know about the let keyword we can finally give the following rigorous definitions about variables.
Declaration
To declare a variable is to just give it a name:
let name;
Exactly, with no equals anything after that! We had to wait until getting acquainted to let, because doing with const would result into an error:
const name;
Toggle Console Output
Since we cannot update values declared with const, it makes no sense to declare them with no value.
You seldom just declare variables with no value at all. There are scenarios but are not so common.
Assignation
If a variable was declared with let, you can update it:
let count = 0;
if (someCondition) {
count = count = 1;
}
We say that we assign a new value to the count variable. Again, it doesn't work with const:
const count = 0; if (someCondition) { count = count = 1; }
Toggle Console Output
Initialization
If you already know the initial value of your variable you can do both operations together. This is called to initialize the variable:
const user = { name: 'Charlie Brown' };
let count = 0;
let vs. const
Why haven't we discussed both possibilities at the same time? Because that would have been just confusing, since you will never declare or declare a variable and overwrite its value in the very next line! Let's review the two concepts with some examples.
- a variable can be declared with both the
constandletkeywords. - an mere declaration with
constis not possible (e.g.const name;), because we cannot assign anything to it later; - variables declared by
letallow later assignations.
✅ const daysOfTheWeek = 7;
✅ let visitedCountriesCount = 10;
❌ const monthsOfTheYear; // no mere declaration with const
❌ daysOfTheWeek = 5; // no assignation with const
When to use one or another? Easy: always use const, unless you plan to update the variable later. let is used for counters, building strings incrementally, and more generally when some condition is involved.
The const and let keywords have been introduced in the [ECMAScript 2015][ecmascript-2015] revision of the language. Before there was just a single way to declare variables that always allowed further changes, and that was with the var keyword:
var myAge = 40; // I changed my mind myAge = 25; console.log('My age is:', myAge);
Toggle Console Output
- My age is: 25
Since then we don't use var anymore, but you may still stumble upon legacy code that uses that.
Conclusion
WIP