DEV Community

Cover image for [JAVASCRIPT] Primitive vs. Reference Data Types
Taemin Kim
Taemin Kim

Posted on

[JAVASCRIPT] Primitive vs. Reference Data Types

In javascript, there are two different data type: primitive and reference

Primitive Types Reference Types
Number Object
String Array
Boolean Function
Null Map
Undefined Set
BigInt(ES6) WeakMap, WeakSet(ES6)

Array, function, map, set, WeekMap, WeakSet are also objects.

Both types of variables have declaration and assignment.

<!-- Primitive Type -->
let name = "kevin";
let age = 20;


<!-- Reference Type -->
let name = {name: "kevin", age: "20"};
Enter fullscreen mode Exit fullscreen mode

Both types of variables are stored in memory at the declaration by using 'let'.

However, assignment works differently for the two variables.

memory diagram

When variables are declared, their values are stored in either a 'stack' or a 'heap'. These memory types will not be covered in this article.

As you can see, the primitive types of variables, "Kevin" and 20 are stored in the stack as values when the reference variable of the object is stored as an address.

Key differences of the two types

  • Primitive variables store primitive values
  • Reference variables store an address
  • The primitive's value is copied
  • The reference's address is copied
  • Primitive values are compared
  • Reference addresses are compared
  • The primitive value is returned
  • The reference's address is returned

As you can see, data is categorized into two different types and the computer store them differently. It is important to understand and identify each type because it is common to face many issues related to the differences in these types.

I hope that you found this article helpful. Feel free to contact me for any questions or comments.

Top comments (0)