Primitive
In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods or properties. There are 7 primitive data types: string, number, bigint, boolean, undefined, symbol, and null.
Most of the time, a primitive value is represented directly at the lowest level of the language implementation.
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 a new value, but the existing value can not be changed in the ways that objects, arrays, and functions can be altered.
Example
Autoboxing: primitive wrapper objects in JavaScript
Due to a feature known as "autoboxing", JavaScript primitives appear to have methods and properties.
For example, below it looks like toUpperCase()
and length
are methods and properties of the string primitive.
let mystring = "lower case string";
console.log(mystring.toUpperCase()); // 'LOWER CASE STRING'
console.log(mystring); // Still 'lower case string' as toUpperCase() didn't modify mystring.
console.log(mystring.length);
// 17
What actually happens is that a wrapper object associated with the primitive is automatically accessed instead.
Except for null
and undefined
, all primitive values have object equivalents that wrap around the primitive values:
String
for the string primitive.Number
for the number primitive.BigInt
for the bigint primitive.Boolean
for the boolean primitive.Symbol
for the symbol primitive.
The wrapper's valueOf()
method returns the primitive value.
Primitives are immutable
This example will help you understand that primitive values are immutable. A primitive can be replaced, but it can't be directly altered.
// Using a string method doesn't mutate the string
let bar = "baz";
console.log(bar); // baz
bar.toUpperCase();
console.log(bar); // baz
// Assignment gives the primitive a new (not a mutated) value
bar = bar.toUpperCase();
console.log(bar); // BAZ
// By contrast, using an array method mutates the array
let foo = [];
console.log(foo); // []
foo.push("plugh");
console.log(foo); // ["plugh"]