DEV Community

Cover image for JavaScript primitives Methods
Bello Osagie
Bello Osagie

Posted on β€’ Edited on

1

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

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay