Skip to main content

constant()

constant<T>(value): () => T

Creates a function that returns value.

DEPRECATED

Use an inline arrow function () => value instead.


Type Parametersโ€‹

T: Tโ€‹

The type of the value.


Parametersโ€‹

value: Tโ€‹

The value to return.


Returnsโ€‹

A function that returns the value.

(): T

Returns: Tโ€‹


Sinceโ€‹

2.0.0


Also known asโ€‹

always (Ramda) ยท constant (Lodash, es-toolkit, Remeda, Effect) ยท โŒ (Radashi, Modern Dash, Antfu)


Exampleโ€‹

// โŒ Deprecated approach
const getDefault = constant({ user: 'guest' });
getDefault(); // => { user: 'guest' }

// โœ… Recommended approach
const getDefault = () => ({ user: 'guest' });
getDefault(); // => { user: 'guest' }

How it works?โ€‹

Creates a function that returns a constant value. Deprecated: Use an inline arrow function () => value instead.

Native Equivalentโ€‹

// โŒ constant(value)
// โœ… () => value

Use Casesโ€‹

Return fixed value ๐Ÿ“Œโ€‹

Function that always returns same value.

const always = (v) => () => v;
const alwaysTrue = always(true);
alwaysTrue(); // => true

Identity functionโ€‹

Return input unchanged.

const identity = (x) => x;
[1, 2, 3].map(identity); // => [1, 2, 3]

Placeholder callbackโ€‹

Default callback that does nothing special.

const defaultTransform = (x) => x;
const transform = options.transform ?? defaultTransform;