JavaScript CONSTANTS

Muhammad A Faishal - Sep 3 '23 - - Dev Community

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
. . . . . . . . . . . .
Terabox Video Player