JavaScript

JavaScript

Made by DeepSource

Avoid the usage of primitive constructor types JS-0488

Type check
Minor

The use of primitive constructor types such as Boolean, Number and String is not preferred.

List of primitive types :

  • boolean
  • string
  • number
  • bigint
  • null
  • undefined (void in Flow types)
  • symbol (new in ECMAScript 2015)

These are not recommended as String is available as a class and has its own prototype methods. We can check those using String.prototype. Also, all primitives are immutable, i.e., they cannot be altered. It is important not to confuse a primitive itself with a variable assigned a primitive value. The variable may be reassigned to a new value, but the existing value can not be changed in the ways that objects, arrays, and functions can be altered.

Example of Immutablility :

var a = 'text'
a.slice(1)
console.log(a) // output: 'text'

There is a difference between number and Number (the same goes for Booleans and Strings). The former (number) is the type of primitive numbers which appear in programs as literals, like 3.14 and 42, or as the result of expressions like parseFloat(input.value). The latter is the type of Number wrapper objects, which are rarely used.

var a = 12
var b = new Number(12)
console.log(typeof a) // "number"
console.log(typeof b) // "object"

Also, they work differently in eval as well. It is recommended to use primitive instead of using the primitive constructor types, for example, string over String

Bad Practice

type x = Number

type x = String

type x = Boolean

type x = { a: Number }

(x: Number) => {}

Recommended

type x = number

type x = string

type x = { a: number }

type x = { a: string }

(x: number) => {}

type x = MyNumber

References