Constants

Some values don't change while a program runs: your date of birth, the number of days in a week, the name of a shop. For such values, JavaScript has constants: variables whose value can't be changed. You create them with the keyword const instead of let:

const daysInWeek = 7;
console.log(daysInWeek);

Once a constant has a value, it keeps it. If a program tries to change it, the program stops with an error. The program in the editor does exactly that. It ran when you opened this exercise, so look at its output: it printed the first line and then stopped with this red message:

TypeError: Assignment to constant variable.

It says that the program tried to assign a value to a constant, that is, to store a value in it with =. The rest of the program didn't run. (This is how Chrome puts it; other browsers word the message a little differently.)

So which one should you use? Use const for values that won't change, and let for values that will. With const, JavaScript itself makes sure that you don't change a value by mistake, and anyone who reads the code can see right away that the value stays the same. From now on, we'll use const wherever a value doesn't change.

In older programs, you may also come across variables created with var. It's an older way of creating variables with a few pitfalls, and today programmers use let and const instead.

Instructions

The price of the pizza changes, so pizzaPrice can't be a constant. Fix the error: create pizzaPrice with let instead of const. The program should print:

Pizza costs 250
Pizza costs 200

The price of a drink won't change. At the end of the program, create a constant drinkPrice with the value 40.

On the last line, print the total price of a pizza and a drink, calculated from pizzaPrice and drinkPrice, like this: Total: 240.

Start programming for free

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

Or sign up with:

Back

7/15

Next