Methods of primitives
Methods of primitives
JavaScript allows us to work with primitives \(strings, numbers, etc\.\) as if they were objects\. They also provide methods to call as such\. We will study those soon, but first we’ll see how it works because, of course, primitives are not objects \(and here we will make it even clearer\)\.
Let’s look at the key distinctions between primitives and objects\.
A primitive
- Is a value of a primitive type\.
- There are 7 primitive types:
string,number,bigint,boolean,symbol,nullandundefined\.
An object
- Is capable of storing multiple values as properties\.
- Can be created with
\{\}, for instance:\{name: "John", age: 30\}\. There are other kinds of objects in JavaScript: functions, for example, are objects\.
One of the best things about objects is that we can store a function as one of its properties\.
let john = {
name: "John",
sayHi: function() {
alert("Hi buddy!");
}
};
john.sayHi(); // Hi buddy!
A primitive as an object
Here’s the paradox faced by the creator of JavaScript:
- There are many things one would want to do with a primitive, like a string or a number\. It would be great to access them using methods\.
- Primitives must be as fast and lightweight as possible\.
The solution looks a little bit awkward, but here it is:
The “object wrappers” are different for each primitive type and are called: String, Number, Boolean, Symbol and BigInt\. Thus, they provide different sets of methods\.
For instance, there exists a string method str\.toUpperCase\(\) that returns a capitalized str\.
Here’s how it works:
let str = "Hello";
alert( str.toUpperCase() ); // HELLO