01 / 05
A variable made inside a function cannot be seen from outside
Bundle up work into functions
INPUT · Slides
01 / 05
A variable made with const or let inside a function's { } can only be used inside that function.
This "how far a variable reaches" is called scope.
The code below errors on the last line. total only exists inside the function, so calling for it from outside finds nothing.
function showTotal() { const total = 500; console.log(total);}showTotal();console.log(total);02 / 05
The other direction works. A variable made outside a function can be seen from inside it.
The outside is visible from the inside; the inside is not visible from the outside. That one-way street is the basis of scope.
const shopName = "Green Store";function showName() { console.log(shopName);}showName();Result
Green Store
03 / 05
What happens if you make variables of the same name inside and out? The answer is that the nearer one gets used.
Inside the function you see the one made inside; outside you see the outside one. This is why changing it inside does not affect the outside.
const label = "outside";function show() { const label = "inside"; console.log(label);}show();console.log(label);Result
inside outside
04 / 05
It is not only functions that make a scope. A variable made with let or const inside an if's or a for's { } also belongs to that { } alone.
The i in for (let i = ...) being unusable outside the loop is the same reason. Putting the gathering variable outside the loop all this time was down to this.
let total = 0;for (let i = 1; i <= 3; i++) { const twice = i * 2; total += twice;}console.log(total);Result
12
05 / 05
Once scope makes sense, a guide to building functions comes into view.
Do that and you never touch an outside variable directly. Carry the function somewhere else and it still works, and it stays easy to follow where a value changed.
Right then, write some with the ranges in mind.
function addTax(price) { const tax = price / 10; return price + tax;}console.log(addTax(800));Result
880