Variable Scope

Inside a function, you can create variables with let and const, just like anywhere else. But such a variable exists only inside the function: it's created when the function runs and disappears when the function ends. Outside the function, JavaScript doesn't know it:

function greet() {
    const message = "Hello!";
    console.log(message);
}

greet();
console.log(message);

This prints Hello! and then ends with the error ReferenceError: message is not defined. The call greet() worked, but the last line looks for message outside the function, where it doesn't exist. Parameters are the same: they exist only inside their function.

The part of a program where a variable exists is called its scope. A variable created inside a function is local: it belongs only to that function. A variable created outside all functions can be used everywhere in the program, inside functions too:

const shopName = "Pet Corner";

function printLabel(product) {
    console.log(`${shopName}: ${product}`);
}

printLabel("dog food");

This prints:

Pet Corner: dog food

Why is it useful that local variables stay inside their functions?

  • Functions don't get in each other's way. Two functions can each have a variable named total, and those are two different variables: changing one doesn't change the other.
  • To use a function, you only need to know what to give it (the arguments) and what it gives back (the return value). How it works inside is its own business.
  • Every call starts afresh: the variables of the function are created again, with nothing left over from the previous call.

So when you need a value from inside a function, don't reach for its variable. Return the value with return and store it where you call the function.

By the way, the same rule applies to every block in curly braces: a variable created with let or const inside an if or a loop exists only in that block.

Instructions

The program ends with the error ReferenceError: total is not defined, because total exists only inside the function. Fix it: return total from the function. Below the function, store the result of the call orderPrice(25, 4) in a variable bill, and print bill instead of total. The program prints 100.

Every order costs an extra 5 for delivery. Above the function, create a variable delivery with the value 5. Inside the function, add it to the total, so that the program prints 105.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

7/10