Differentiating among JavaScript Object, Primitive, and Literal
This article will make it clear, no more confusion, on to the concept.
Literal
Literal means a value. A value of any of the following.
String
Number
Boolean
"I love javascript" is a string literal, 50.725 is a number literal, and false or true is a boolean literal.
Primitives
Primitives are the instances of any data type. And there are five data types.
String
Number
Boolean
null
undefined
Three of the above (String, Number and Boolean) data types have complementary objects. And objects allow more properties on each data-typed variable.
"I love Javascript"
is a literal.
String("I love Javascript")
is a primitive.
new String("I love Javascript")
is an object.
50.725
is literal.
Number(50.725)
is primitive.
new Number(50.725)
is an object.
true
is literal.
Boolean(true)
is primitive.
Literal is just a value, nothing else. Now, we are left with Primitive and Object. And they both are not the same.
Take a look at the following code snippet.
let str1 = String("I am a primitive string.");
let str2 = new String("I am an object!");
console.log(typeof(str1)); // string
console.log(typeof(str2)); // object
console.log(str1 === "I am a primitive string."); // true
console.log(str2 === "I am an object!"); // false
console.log(str2.toString() === "I am an object!"); // true
All the code above seems tricky, but just remember, Primitive and Object are not the same.
Primitive variables (without new keyword), are strictly equal to literals. This is because primitives are compared by value, and values are literals.
On the other hand, objects are not compared by value, they are compared by reference. (More on this later...)
Take a look at the following code.
let str1 = String("javascript"); // primitive
let str2 = new String("javascript"); // object
console.log(typeof(str1)); // string
console.log(typeof(str2)); // object
This seems a bit confusing, but things will be clear as we go ahead.
Keep readin, thanks!