Introduction to Methods of Primitives in JavaScript
In JavaScript, primitive values (number, string, boolean, null, undefined, and symbol) are the fundamental building blocks of data.
Despite being basic and immutable, JavaScript provides a way to call methods on primitive values, giving them capabilities that seem more characteristic of objects.
This fascinating feature is made possible through temporary object wrappers, allowing developers to perform various operations on primitive values seamlessly
How Methods Work on Primitives
JavaScript internally converts primitive values to their corresponding object types when a method is called on them. This process involves creating a temporary wrapper object, invoking the method on this object, and then discarding the object, leaving the original primitive value unchanged.
- Number: Wrapped by
Number
object. - String: Wrapped by
String
object. - Boolean: Wrapped by
Boolean
object. - Symbol: Wrapped by
Symbol
object.
Methods of String Primitives
String primitives have a rich set of methods for manipulation and interrogation.
- Length of the string
- Changing case
- Accessing characters
- Finding substrings
- Extracting substrings
- Splitting strings
- Replacing substrings
Methods of Number Primitives
Number primitives have methods mainly for numerical operations and formatting.
Common Number Primitives:
- Fixed-point notation
- Exponential notation
- Precision formatting
- Converting to string
Methods of Boolean Primitives
Boolean primitives have fewer methods, primarily focused on conversion.
Common Boolean Methods: Converting to string
Methods of Symbol Primitives
Symbols, introduced in ES6, are unique and immutable. They have a limited set of methods.
Common Symbol Methods:
- Converting to string
- Getting the description