-1

How do you declare and initialize constant variables in javascript?

Venkat
  • 50
  • 4
  • [MDN const](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) – epascarello Apr 17 '20 at 17:30
  • [Object.freeze()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) is maybe also relevant depending on what you want to achieve with it. – t.niese Apr 17 '20 at 17:34

1 Answers1

-1

You use the keyword const to declare a constant in javascript. Here is an example:

    const CLASS_COUNT = 35;

Here CLASS_COUNT is a constant variable. You can not assign a different value to CLASS_COUNT. As per convention, use capital letters to name a constant variable.

It is possible that the value which is assigned to a const can itself be changed, if the value is mutable. For eg.

    const PERSON = {location: 'USA'};
    PERSON.location = 'INDIA';

In the above example, PERSON is assigned an object whose location is 'USA'. But in the next statement, the object's property location is changed to 'INDIA'. This is possible because the object that is assigned to const PERSON is mutable.

Beware that the following code is WRONG:

    const PERSON = {location: 'USA'};
    PERSON = {location: 'INDIA'};  // This will fail.
Venkat
  • 50
  • 4
  • `Its value can not be changed`, that's a bit misleading. `const` in JavaScript means that thich value is assigned to the variable cannot be changed, but it does not mean you cannot do changes to the value. So if you have `const test = {}` you can for sure do `test.foo = 1`. – t.niese Apr 17 '20 at 17:33
  • 2
    @t.niese That's not misleading, but more of a misunderstanding. The element in memory that `test` points to remains constant. It's simply the case that that element in memory is mutable, which is a different thing entirely. – Taplar Apr 17 '20 at 17:36
  • I completely agree with @Taplar – Venkat Apr 17 '20 at 17:42