Primitives are fundamental data types like strings, numbers, booleans, etc. These primitive data types can be worked on as objects (non-primitive).
For example, a method on an object. See the syntax below:
object.method()
A method can also work on primitive data.
Let's assume the primitive data type is pmt
:
pmt.method()
The syntax above is true because an instance is an object which resides in memory at runtime.
An instance is an object in a class.
We will see classes in future articles.
A method that works on an object may not work on primitive data.
See the example below:
const str = "Hello";
console.log( str.toUpperCase() ); // HELLO
Accessing the str
means the creation of a new object (instance of the string) that knows the value of the string (saved value in memory). The object also contains useful methods like toUpperCase()
toLowerCase()
etc. The object gets destroyed once the result (HELLO
) is retrieved.
Since objects have properties, there are properties like length
.
const str = "Hello";
console.log(str.length); // 5
.length
counts the number of characters in a string, str
.
Methods like toUpperCase()
are functions in an object. The function may contain properties like length
- Every data type has its object.
See the example below:
const num = 1.23456;
console.log( num.toFixed(2) ); // 1.23
The most primitives
null
andundefined
are exceptions because they have no corresponding wrapper objects (no methods and properties).
Happy coding!!!
Top comments (0)