Get to know all the practical knowledge about Javascript primitives and objects.
In JavaScript, objects are king. If you understand objects, you understand JavaScript.
- W3 Schools
Everything except primitives is an object in Javascript. A couple of days back, we were talking about Javascript having the following primitives: bool, number, string, undefined and null.
Primitives are quite easily defined and accessed -
|
|
Objects on the other hand.. can also be easily defined and accessed.
|
|
Objects have properties, or props as they are affectionately known.
|
|
Things become interesting in Javascript when primitives are also treated as objects.
|
|
This is true for other types as well. Consider the below example of a string.
|
|
Javascript internally manages to make primitives behave as objects (“coerces”, or “applies coercion”) when we try to do such things in our code.
So, should we just treat any primitive as an object and go wild?
Emm.. no. You cannot set props against a primitive for one.
|
|
You can do that quite easily for an object.
|
|
You will not find differences in real-world programming - since you naturally keep them separated :). But it is important to know why you do that distinction.
So, what should you use in your code - primitives, objects, or primitives disguised as objects?
- Use primitives when available
We know, understand and love the variable for what they are, and not what they hide. - Use objects for rest of the circumstances
- Do not mix and match, i.e., start with primitives and change them to be objects later in the program. Although you feel adventurous on a specific day, you will be left high and dry when trying to debug strange behaviours that could destroy humanity