Bundle up work into functions

INPUT · Slides

How far a variable reaches

01 / 05

A variable made inside a function cannot be seen from outside

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

An outside variable can be seen from inside

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

Use the same name and the inner one wins

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

The inside of any { } is a range too

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

Trade through parameters and return values

Once scope makes sense, a guide to building functions comes into view.

  • values a function needs, it catches as parameters
  • results a function produces, it sends back as a return value

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