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

Do your career a favor. Join DEV. (The website you're on right now)

It takes one minute and it's free.

Get started

You have a minute, right?

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay