javascript - object vs. primitive - Stack Overflow
Confusion between Objects and primitive data types in Js
Everything in JavaScript is an object...what about primitive data types?
If string is a primitive then why does it list a bunch of methods when I print out it's prototype?
What are data types in JavaScript?
What are the different data types in JavaScript?
How many data types are there in JavaScript?
Videos
A primitive is a data type that is composed of no other data types and can not be broken down any further. It is like the atoms in the programming scenario. I say atom because atom is a basic unit of matter and there is nothing that can be derived from it.
I mean, an int in C can not be broken down into smaller data type. An object, on the other hand can be thought of a molecule, consisting of more than one primitive type. For example, string comes as part of the C++ standard library; however, it is an object and it is composed of smaller data types internally and contains methods.
It is important to note that not all object-oriented languages are class based (eg. Javascript) You can not define a class in Javascript, so an object is quite different here. Even though everything in Javascript is an object (Ruby also), the Number object is really a wrapper for an internal primitive.
From Java perspective:
- A primitive is not composed of other data types. Where as an object can be and generally is.
- Primitives are passed by value, i.e. a copy of the primitive itself is passed. Whereas for objects, the copy of the reference is passed, not the object itself.
- Primitives are independent data types, i.e. there does not exist a hierarchy/super class for them. Whereas every Object is descendent of class "Object".
- Every object has some default methods of itself, which it inherits from the class Object (e.g. toString(), clone(), wait(), notify(), notifyAll(), etc.). The primitives does not have any method associated with themselves.
- Primitives are immutable, they can be used as so without any special care. Whereas for objects, special care needs to be taken, they are not immutable by default.
- With objects, there are two types of copies, Shallow and Deep. There is a significant difference between them. So the choice depends on how do we intend to use them. With primitives, there is no such difference, everything is by default deep copy only.