DEV Community

Cover image for JavaScript primitives Methods
Bello Osagie
Bello Osagie

Posted on • Edited on

JavaScript primitives Methods

image.png


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()
Enter fullscreen mode Exit fullscreen mode

A method can also work on primitive data.

Let's assume the primitive data type is pmt:

pmt.method()
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

.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
Enter fullscreen mode Exit fullscreen mode

The most primitives null and undefined are exceptions because they have no corresponding wrapper objects (no methods and properties).

Happy coding!!!


image.png


image.png

Top comments (0)