A primitive (primitive value, primitive data type) is data that is not an object and has no methods. In JavaScript, there are 6 primitive data types: string, number, boolean, null, undefined, symbol (new in ECMAScript 2015).

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

This example would help you understand the fact that primitive values are immutable.

JavaScript

// Using a string method doesn't mutate the string
var bar = "baz";
console.log(bar);               // baz
bar.toUpperCase()
console.log(bar);               // baz

// Using an array method mutates the array
var foo = [];
console.log(foo);               // []
foo.push("plugh");
console.log(foo);               // ["plugh"]

// Assignment gives the primitive a new (not a mutated) value
bar = bar.toUpperCase();       // BAZ

A primitive can be replaced, but it can't be directly altered.

Another Example [ Step-by-step ]

The following example will help you going through how JavaScript deal with Primitives:

JavaScript

// The Primitive 
let foo = 5;

// A function to change the Primitive value
function addTwo(foo) {
   foo = foo + 2;
}

// Pass our Primitive as an argument to `addTwo()` function
addTwo(foo);

// Get the current Primitive value
console.log(foo);   // 5

Did you expect it to be 7 instead of 5? If so, read how this code runs:

  • When we invoked the function, JavaScript was looking for the argument that we have passed - foo
  • After finding it, JavaScript passed that argument to the addTwo() function as an argument
  • Before doing ANYTHING inside the function, JavaScript took a copy of the original passed - Primitive - argument to work with it inside our function
  • Let's add 2 to the current foo value
  • Any changes inside our function won't affect the ORIGINAL foo at all, as we are working on our COPY of it

That's why Primitives are Immutable. Because, we aren't working on them directly, we took our copy and keep working with it, without touching the original one.

Be aware that when we use foo, inside the function, it refers to foo the parameter   -   addTwo(foo)  not foo - the variable - let foo = 5;

Primitive wrapper objects in JavaScript

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.
  • Boolean for the Boolean primitive.
  • Symbol for the Symbol primitive.

The wrapper's valueOf() method returns the primitive value.

Learn more

General knowledge

Document Tags and Contributors

Last updated by: elharony,