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!"
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");
Other uses
Besides defining data types, const
is widely used in various other contexts.
a. Destructuring Arrays
const [a] = ["a"];
b. Destructuring Arrays with Default Values
const [a = 0] = [];
c. Destructuring Objects
const { a } = { a: "value" };
d. Destructuring Objects with Default Values
const { a = "default" } = {};
e. Global Constants
// Browser environment
window.GLOBAL_CONSTANT = "This is a global constant";
// Node.js environment
global.GLOBAL_CONSTANT = "This is a global constant";
f. Environment Variables (Node.js)
const PORT = process.env.PORT || 3000;
g. Template Literals with Constants
const name = "John";
const greeting = `Hello, ${name}!`;
h. Rest Parameters in Functions
function sum(...numbers) {
const result = numbers.reduce((acc, num) => acc + num, 0);
return result;
}
i. Destructuring Function Parameters
function printUser({ name, age }) {
console.log(`Name: ${name}, Age: ${age}`);
}
j. Class Constants
class Circle {
constructor(radius) {
this.radius = radius;
}
getArea() {
const PI = 3.14159;
return PI * this.radius * this.radius;
}
}