DEV Community

Cover image for JavaScript CONSTANTS
Muhammad A Faishal
Muhammad A Faishal

Posted on

JavaScript CONSTANTS

In JavaScript, most of developers are well-known with const. It declares block-scoped local variables which means the value of a constant can't be changed through reassignment using the assignment operator.

However, have you defined the constant properly and clearly?

Naming Convention

According to Airbnb Naming Uppercase, exported constants should follow SCREAMING_SNAKE_CASE format, but not for constants within a file.

// Within a file const helloWorldText = "Hello, World!" // Exported constants export const HELLO_WORLD_TEXT = "Hello, World!" 
Enter fullscreen mode Exit fullscreen mode

Examples

The following are examples of all exported data type constants:

// Number const PI = 3.14159; // String const GREETING = "Hello, World!"; // Boolean const IS_ACTIVE = true; // Array const COLORS = ["red", "green", "blue"]; // Object const PERSON = { name: "John", age: 30 }; // RegExp const EMAIL_PATTERN = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; // Null const NO_VALUE = null; // Undefined const UNDEFINED_VALUE = undefined; // Symbol const UNIQUE_KEY = Symbol("unique"); 
Enter fullscreen mode Exit fullscreen mode

Other uses

Besides defining data types, const is widely used in various other contexts.

a. Destructuring Arrays

const [a] = ["a"]; 
Enter fullscreen mode Exit fullscreen mode

b. Destructuring Arrays with Default Values

const [a = 0] = []; 
Enter fullscreen mode Exit fullscreen mode

c. Destructuring Objects

const { a } = { a: "value" }; 
Enter fullscreen mode Exit fullscreen mode

d. Destructuring Objects with Default Values

const { a = "default" } = {}; 
Enter fullscreen mode Exit fullscreen mode

e. Global Constants

// Browser environment window.GLOBAL_CONSTANT = "This is a global constant"; // Node.js environment global.GLOBAL_CONSTANT = "This is a global constant"; 
Enter fullscreen mode Exit fullscreen mode

f. Environment Variables (Node.js)

const PORT = process.env.PORT || 3000; 
Enter fullscreen mode Exit fullscreen mode

g. Template Literals with Constants

const name = "John"; const greeting = `Hello, ${name}!`; 
Enter fullscreen mode Exit fullscreen mode

h. Rest Parameters in Functions

function sum(...numbers) { const result = numbers.reduce((acc, num) => acc + num, 0); return result; } 
Enter fullscreen mode Exit fullscreen mode

i. Destructuring Function Parameters

function printUser({ name, age }) { console.log(`Name: ${name}, Age: ${age}`); } 
Enter fullscreen mode Exit fullscreen mode

j. Class Constants

class Circle { constructor(radius) { this.radius = radius; } getArea() { const PI = 3.14159; return PI * this.radius * this.radius; } } 
Enter fullscreen mode Exit fullscreen mode

Top comments (5)

Collapse
 
efpage profile image
Eckehard • Edited

Everybody can define itΒ΄s own naming conventions, so there is nothing wrong to do it differently, as long as you are not employed by AirBNB.

But although you mentioned this in a subordinate clause, it could be useful to go a bit more into detail about the strange behavoir of constants in Javascript, as they behave differently from constants in most other languages:

const c = [1, 2] // defines a constant c c[1] = 3 // this works, c = [1,3], value was changed c = [3, 4] // this gives you an "Uncaught TypeError" const [a,b] = [1,2] // defines 2 constants  const {e,f} = [1,2] // -> e,f -> undefined, but no error const {a,b} = {a:1,b:2} // a=1, b=2 const {e,f} = {a:1,b:2} // e,f=undefined, but no error const h = {a,b} // h = {a: 1, b: 2} const {i,j} = {1,2} // error: unexpected number const l = (x) => console.log(x) // defines a function 
Enter fullscreen mode Exit fullscreen mode
Collapse
 
maafaishal profile image
Muhammad A Faishal • Edited

Yes, the naming convention is preference, but it's recommended to follow for constants.

I see, let me add some const implementations. Thanks for the feedback!

Collapse
 
efpage profile image
Eckehard

Great, this makes your post much more valuable, thank you!

There is one other strange thing about Javascript with reference to "const": While this is usable in normal Javascript, you cannot use it in object- or class variables. So, I suppose, your example j. is not correct, as this is a local constant, not a class constant. A class const was most useful, but it is not allowed:

class Circle { const PI = 3.14159; // --> Unexpected identifier 'PI' constructor(radius) { this.radius = radius; } getArea() { return PI * this.radius * this.radius; } } 
Enter fullscreen mode Exit fullscreen mode

The same is true for object properties, that are always mutatable and cannot be defined using const, let or var. This is a very serious limitation of the JS class concept, as you cannot protect your internal variables against mutation.

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

...the value of a constant can't be changed through reassignment using the assignment operator, except Object and Array.

This is not correct, a const containing an Object or Array cannot be reassigned either. However, properties and contents of those types CAN be changed - but this is not reassignment.

Collapse
 
efpage profile image
Eckehard

You are right, but this is unexpected for users that came from other languages. The keyword "const" suggests, that the value cannot be mutated. So it is not obvious, why this is different:

const c = 5 const d = [5] d = 6 // --> Error d[0] = 6 // --> ok 
Enter fullscreen mode Exit fullscreen mode