Languages
[Edit]
EN

JavaScript - constants

0 points
Created by:
user4838
668

In this article, we would like to show you how to declare and use constants using the const keyword in JavaScript.

Syntax

const myConstant = value;

Description

Constants are declared using the const keyword and they must be initialized. They are block-scoped such as variables declared using the let keyword. The constant values can't be changed through reassignment, and they can't be redeclared. However, if you create a constant object or array its properties or items can be updated or removed.

Practical examples

Example 1

In this example, we create a constant and try to reassign a value to it.

// ONLINE-RUNNER:browser;

const myConstant = 1;

try {
  myConstant = 2;
} catch (error) {
  console.log(error); // TypeError: Assignment to constant variable.
}

console.log('myConstant = ' + myConstant); // 1

Output:

TypeError: Assignment to constant variable.
number = 1

Example 2

In this example, we create an uninitialized constant.

// ONLINE-RUNNER:browser;

const myConstant;

Output:

Uncaught SyntaxError: Missing initializer in const declaration

Example 3

This example shows, that constants are block-scoped.

// ONLINE-RUNNER:browser;

const myConstant = 3;

if (true) {
  const myConstant = 2;
  console.log(myConstant); // Output: 2
}

console.log(myConstant); // Output: 3

Output:

2
3

References

  1. const - JavaScript | MDN

Alternative titles

  1. JavaScript - const keyword
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - Statements & declarations

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join