DEV Community

Koichi
Koichi

Posted on

The difference between primitives and objects in JavaScript

What are data types in JavaScript

JavaScript has several data types to represent a variety of values. These types are mainly categorized into 2 types: primitive types and object types.

The understanding of the difference

The fundamental data types are treated as primitives, and the others are considered objects. Objects can contain multiple primitives values as a data set and also have methods.

Primitives:

  • Fundamental data type
  • Single value
  • Immutable - can not be modified
  • Does not have methods and properties
  • Stored in stack memory

Objects:

  • Complex data type
  • A data collection have multiple values
  • Mutable - can be modified
  • Consists of properties and methods
  • Stored in Heap memory

Primitives

These are primitive types:

  • number
  • string
  • boolean
  • null
  • undefined
  • symbol

Primitive data types are immutable, meaning that their values cannot be changed once they are created.

Objects

An object is a complex data type that represents a collection of properties and methods. A method is a function, a process of logic. Objects are also known as reference types. The actual data is stored in Heap memory, and a variable holds the location information of the reserved area.

If you want to know more about memories, this article must help your understanding:

Wrapper objects

Even though primitives have neither properties nor methods, we can act to access them.
Example:

"string".length; // 5
"lower".toUpperCase() // LOWER
Enter fullscreen mode Exit fullscreen mode

That is because of the implicit support of objects called wrapper objects. Wrapper objects exist globally and help primitive types. Their names are quite similar to the data type, like Number or String. Their spells start in upper-case. When a script attempts to access a property of a primitive value, JavaScript automatically creates the wrapper object around the primitive value to provide access to these properties.

Conclusion

The main difference between primitives and objects is that primitives are simple, immutable values, while objects are complex, mutable entities that can contain properties and methods. To understand the difference seems hard; however, it must help your developer life!

References

Top comments (0)