๐ŸŽ“ A1Learner
๐Ÿ”

JavaScript Const

const is the keyword that declares a value that cannot be reassigned. A const name keeps the same value for the whole program.

A fixed price

const declares price with the value 25. The value of a const name stays fixed after this line.

const price = 25;
console.log("Price:", price);

Two fixed values

One program can hold many const names. Each name keeps its own fixed value.

const shop = "Book Nook";
const price = 25;
console.log(shop);
console.log(price);

Values side by side

console.log can print a label and const values in one call. The console joins the parts with spaces.

const item = "Pen";
const price = 3;
console.log(item, "costs", price);

Example

const shop = "Book Nook";
const bookPrice = 25;
const penPrice = 3;
console.log(shop);
console.log("Book:", bookPrice);
console.log("Pen:", penPrice);

Key points

  • const declares a name and its value on the same line.
  • A const declaration without a value is an error.
  • Reassigning a const raises a TypeError, an error that reports a wrong use of a value.
  • var: the old keyword for declaring variables
  • Use const for a value that never changes.

In this example, the first statement fixes the shop name as Book Nook. The next two statements fix the two prices. The last three statements print the name and both prices, one line each.

Try it Yourself

Edit the code, then press Run.

Runs in your browser โ€” the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

Which statement about const is true?