- The learner should understand the concept of variable scope and be able to define them in global, local and block scope
- The learner should be able to use destructuring to extract data from arrays
- The learner can describe why you would want to use array destructuring
The purpose of this class is to introduce to the trainee:
- The scoping of variables, specifically in reference to:
- Array Destructuring
- Project Work
Variables are amazing! Variables let us store data and reuse it many times rather than writing the same data over and over again, also if the variables are well named then it makes it much easier to think about what our code is doing.
As we know, after we declare or define a new variable we can refer to it later in our code using the variable name.
Now, imagine what would happen when our code gets really long. Every time we want to define a new variable we have to check that it hasn't already been used for something else. If that variable is already being used and we redefine it, bad things can happen. We could overwrite something important.
Imagine a banking app being built by two developers. Developer 1 uses the variable name
money to store the total amount of cash a single customer has in the bank, Developer 2 uses the variable name
money to store the total amount of cash that ALL customers have in the bank added together, the total money in the bank's vaults. This could be really good news for a customer who accidentally receives the entire bank's money in their account, but really BAD news for us as the owners of a bank.
One solution might be that every time we want to create a new variable, we call around all of the other developers on the project and ask them if it's safe to use the variable name
money. We can quickly see a problem with this, some codebases are millions of lines long! No single person knows what is contained in every file. It would be impossible to know what variables are safe to use and which are not.
Instead, we need to find a way to make variables safer. We need a way to use the best variable name to describe our data, without worrying that we will be causing problems in a different part of the codebase.
We call this
Think about the way that laws are set in different countries. Most laws are set by the government of that country and are
local to that country. However, some laws are international, laws like 'no slavery' apply across all countries, these are
In some countries, different regions inside the country can set their own laws too. In America you must be 21 to drink (national law), but in the state of Massachusetts all bars must be closed by 2AM (state law). These are two levels of local laws.
In Massachusetts, a citizen must follow all 3: International Law, National Law and State Law.
But a pirate 🏴☠️ in the middle of the ocean only needs to follow International Law (and perhaps the law of the Ship).
In the same way we think about which laws apply to which parts of a country we must also think about which variables apply to which parts of your code. Variables, like laws, only apply to a certain area.
ReferenceError telling us that a variable is not defined.
In the example above, the State Law only applies to Massachusetts. When we try to
stateLaw variable at the end, it is not defined. This part of your code does not even know this variable exists!
Variables declared outside of any function or code block are available throughout an application. They are referred to as global variables and exist in global scope.
We can see in the previous example that
globalLaw is a global variable.
Because global variables are visible by throughout the application, data stored in them can be read and updated by any part of your code. At first this might seem convenient, but in practice this is likely to cause problems in longer term as your code base grows.
- It may not be obvious where in your code global variables are used, which can make refactoring hard
- Other part of your code may accidentally overwrite values in global variables and lead to bugs.
Because of above it is good engineering practice to only use global variables when absolutely necessary.
Note that you can also declare a global variable by assigning to a variable without declaring it with a
Be sure to keep an eye out for above problem and avoid it.
Let's rewind and look at this in detail. We know that variables are declared using the
If we define a variable inside a function, it becomes local to that function. If we want to use a fancy word, we can also say it becomes scoped to that function.
console.log(greeting) on the last line throws an error, it tells us that "greeting is not not defined". Why is this? Because the variable
greeting was defined in the
greetUser function, it does not exist outside the function.
This lets us do new things with variables. You cannot usually create two variables with the same name. For example:
But in the same way countries have own laws, functions have own
scopes! And so it becomes possible to use the same variable name for different situations.
We have used the variable name
greeting twice but it's very important to remember that these are not the same variable! The two variables called 'greeting' do not even know each other exist.
It is important to note that scope is nested. That means when you have one function inside another function, you can access variables defined in outer function from the inner function. However you cannot access variables defined in inner function from outer function.
A block is piece of code inside by curly brackets, for example following
if statements and
- Variables declared using
varkeyword use function scope. That means variables defined using
varexist within function they are defined in.
- Variables declared using
constkeyword use block scope. Variables defined using
constkeywords exist within the block they are defined in.
Any time you define a variable inside a block, that variable cannot escape that block. We say the variable is
scoped to that block.
Scope allows us to control where our variables can be accessed from. We want to ensure that variables are available where they are needed and ideally as little as possible elsewhere to prevent naming collisions or accidental updates. As a result using
const is preferrable to using
var since they has stricter scope definition.
In small groups answer the following the questions.
You also learnt that you can retrieve a value from an Array by using the index of the value to access it.
We have the names of the Simpsons family stored in an array called
familyMembers. Create variables to store the names of the family members so that the
console.log will print out the following message:
In the Simpsons family, Homer and Marge are the parents. Bart is the son, Lisa is the daughter, and Maggie is the baby.
Question: How many lines of code did you add?
There is a way to extract all the values of an array into variable in just one line of code. This technique is called destructuring and it has a special syntax.
Here is the code we used in the last exercise with array destructuring.
With array destructuring you were able to reduce this code down from 7 lines of code to just 3 lines of code. This means your code is shorter and there is less chance for you to have a bug in your code.
Rewrite the code below to use array destructuring instead of assigning each value to a variable.
We have a function called
sumAndMultiply. It will take two numbers and then return an array where the first number is the sum of the two numbers, and the second number is the multiplication of the two numbers.
Which of the following lines of code can be used above?
- A) let sum, multiply = sumAndMultiply(2, 3);
- B) let [sumAndMultiply] = sumAndMultiply(2, 3);
- C) let [sum, multiply] = sumAndMultiply(a, b);
- D) let [sum, multiply] = sumAndMultiply(2, 3);
When you do array destructuring, the array can be of any data type. Try destructuring with the next array, which contains objects.
Complete all of the exercises found here
Here are some useful resources to help you understand this material
- FreeCodeCamp's Intro To Array Destructuring
- Why Is Array/Object Destructuring So Useful And How To Use It (Video)
- The Most In-Depth Yet Understandable ES6 Destructuring Tutorial
For the rest of the day we'll be working together on our group projects
You can find the project here
Trainees should group into teams based on the Level that they are working on currently.
Click here to view the homework for this lesson.
Please spend two minutes reviewing this lesson to help us improve it for the future. This feedback will be shared with volunteers.