Literals VS Objects
I'm curious learner who loves programming & every freaking things about tech. 👩💻👩💻
JavaScript is a weird language! Right?? Every concept here somehow ends up with objects. All the primitive (literals) types that shouldn’t act as objects would start acting as objects if you use keywords like “new” in primitive data type declaration. If you’re learning JavaScript and loving its weird functionality like me then you must’ve wondered for once at least Why the hell is it that way?? Well…. don’t worry fellow friend!! I tried to clear this concept in my head fully and now I’m here to help you get this as crystal clear as possible. Firstly, I will give you some brief details on the difference between literals and objects:
**Literals**
(1)Literals are immutable you can’t add properties in literals.
(2)Literals only hold value.
(3)Literal has no method.
(4)Cannot create two different literals with the same value.
**Objects**
(1)Objects are mutable you can add properties and methods in objects.
(2)Objects have the ability to hold different properties.
(3)Object has methods.
(4)You can create new objects with the keyword ‘new’.
There are so many types of literals or primitives in JavaScript (e.g – Undefined, Booleans, Numbers, Strings, Symbols & BigInt). I will only talk about one primitive type here and that will be “Strings” because I find it to be the easiest for making myself understand how literals are converted to objects & behave like objects. Let’s talk about Strings as literals now……
String Literal: The string with a small ‘s’ is kind of literal. Literals are values that hold no properties. Literals can be converted to objects using a wrapper.
Syntax:
var test1 = "Here’s a literal kinda 'string'";
String Objects: Strings when acting as objects holds many properties and also methods corresponding to them.
Syntax:
var test2 = new String('It’s an object');
Let me give you another code example for helping you understand what I’m trying to say here: Example Code:
<script>
let a = new String("An object !");
let b = "A literal ! haha";
console.log(typeof(a));
console.log(typeof(b));
</script>
Output:
object
string
In the above code if you declare another property to the variable 'a' it will create a new memory for the new property, whereas variable 'b' cannot hold any property so we can’t declare any property with the same variable name 'b'. But 'b' can be converted to an object when a method is called through it.
If you read it this far, please give your valuable feedbacks in the comment section. Plus if you want to reach me out here’s my instragram & Twitter links: Instragram Twitter
