Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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

  1. 1

    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
  2. 2

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

  3. 3

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

Back

7/15

  1. 1. Printing
  2. 2. Arithmetic Operations
  3. 3. Comments
  4. 4. Variables
  5. 5. Changing a Variable's Value
  6. 6. Quiz: The Order of Commands
  7. 7. Constants
  8. 8. Division and Remainder
  9. 9. Joining Text
  10. 10. Text and Numbers
  11. 11. Quiz: Text and Numbers
  12. 12. Template Literals
  13. 13. Quiz: Template Literals
  14. 14. Reading Errors
  15. 15. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.