DEV Community

Cover image for Primitives values and JavaScript Objects
Hozan
Hozan

Posted on

Primitives values and JavaScript Objects

“In JavaScript, objects are king. If you understand objects, you understand JavaScript.” (w3schools)

All JavaScript values such as Arrays, Functions, Objects and Regular Expressions are considered to be objects, except primitives values, these are not objects.

Primitives values are values that have no properties or methods, and the following is a list of what is called primitives data types ,which are a type of data that have primitives values :
• string
• number
• boolean
• null
• undefined

So for example, if we have a string that says “I am a string” , the primitive value in this case is “I am a string” and the primitive data type is string.

But you might ask, if primitives values or primitives data types have no properties or methods, then how come the primitive value “I am string” have property length and other methods such as charAt().

Well first we need to know what is a String object.

A String object, is a JavaScript built-in object, this String object also have a property called 'prototype', this property value itself acts as a template object that contains methods and properties we can use and can be inherited.
Hence the reason we have methods such as String.prototype.charAt().

In JavaScript and other programming languages, they have the ability to convert a value from one data type to another (e.g numbers to strings, or a string to an object).

This kind of a conversion is called coercion , and it is done automatically. And to achieve that all we have to do is use a property accessor such the dot or the bracket notation, to coerce the string value “I am a string” to a String object.:

“I am a string”.charAt(3) // “a”

It is also important to know that primitive values are immutable, so what is happening in background is that the string is temporarily converted to a String object.

new String(“I am a string”).chartAt(3) // “a”

in the example above, the String () function is called a “constructor function” since its name starts with a capital letter.
Having the new operator in front of a constructor function, will create a new object.

In our case here, String() is JavaScript built-in constructor (or object).

That’s why you can also use a constructor functions to make objects instead of using object literal as show in the example below:

Object literal :

var myCar = {
    make: 'Ford',
    model: 'Mustang',
    year: 1969
};
Enter fullscreen mode Exit fullscreen mode

Constructor functions:

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}

var mycar = new Car('Ford', 'Mustang', 1969);// same object as mycar in object literal

Enter fullscreen mode Exit fullscreen mode

Read more about constructor functions here or String object here and if you have any suggestions or feedback, feel free to leave them below.

Top comments (0)