Complete guide to primitive and reference types in Javascript

In this article, I will cover primitive and reference data types in Javascript.

ECMAScript variables can contain two types of data:

  • Primitive types
  • Reference types

Primitive

Primitive values are simple immutable atomic pieces of data.

  • undefined
  • null
  • boolean
  • string
  • symbol

Above are the six primitive types that are offered by Javascript.

Primitive types are immutable means they can not be changed.

let name = "Pratap";
name Pratap

This is how Pratap is stored in the memory when you assign it to the variable name.

let name = "Pratap";
let name2 = name;

If we assign the variable name to another variable name2, it is stored as a separate value and can be used separately with no side effects.

New space allocated in memory

name Pratap
name2 Pratap

Reference

Reference values are mutable objects made of multiple values.

  • arrays
  • functions
  • objects

Javascript has three data types that are stored as reference values.

Reference types are mutable, which means they can be changed.

let person = {
  name: "Pratap",
  age: 20,
};

The above object can be changed or is mutable because the new object will be just the reference to the original object.

Example from the previous object

let person2 = person;
person2.name = "Sidhart";

console.log(person2);
// {name: "Sidhart", age: 20}

To sum it up

This is it from this article. I hope I'm able to give you an overview of primitive and reference data types in Javascript.

💌 If you'd like to receive more tutorials in your inbox, you can sign up for the newsletter here.

Please don't hesitate to drop a comment here if I miss anything. Also, let me know if I can make the post better.

Discussions

Up next