JavaScript Primitive vs. Reference Types

In JavaScript, we see two kinds of data types. The primitive data types and reference data types. Following are some facts about JavaScript data types:

  • Primitives are passed by value, and objects are passed by reference.
  • JavaScript has two kinds of data types: primitive and reference.
  • A fixed amount of memory is reserved after the creation of every variable.
  • Passing a variable to a function via a call also creates a copy of that variable.
  • When a variable is copied, its in-memory value is copied.

Primitive Types

A primitive is a data that is not an object and has no methods. In JavaScript, there are 7 primitive data types. Those are:

  • string
  • number
  • bigint
  • boolean
  • undefined
  • symbol
  • null.

Facts about primitive data types

  • All primitives are immutable which means they cannot be altered
  • Primitives are passed by value
  • The primitives variable may be reassigned to a new value, but the existing value can not be changed
  • Primitive types are also known as: scalar types or simple types

Copy primitive type

let boyAge = 21 ;      // assign `21` to `boyAge`
let girlAge = boyAge;  // copy the value of `boyAge` to `girlAge`
girlAge = 18;          // assign a new value `18` to `girlAge`
console.log(boyAge)    // => 21

Referece Types

A reference type can contain the reference itself which means a memory address.

  • Object
  • Array
  • Function

Copy reference type

const user = { name: 'Joe' }; // assign the reference of a new object to `user`
const femaleUser = user;      // copy the reference of the object inside `user` to new variable `femaleUser`
femaleUser.name = 'Jennifer'; // modify the contents of the object `femaleUser` refers to
console.log(user)             // => { name: 'Jennifer' }
Reference: