Hey Welcome Techies👋🏼
Hello everyone, my name is Aryan Sharma, and I hope you're all doing well.
I'm thrilled to begin this JavaScript blog on for absolute beginners.
You can find my other blogs on JavaScript here↗️
Methods of primitives
JavaScript allows us to work with primitives (strings, numbers, etc.) as if they were objects. They also provide methods to call as such. We will study those soon, but first we’ll see how it works because, of course, primitives are not objects (and here we will make it even clearer).
Let’s look at the key distinctions between primitives and objects.
Primitive:
string
,number
,bigint
,boolean
,symbol
,null
andundefined
.Object:
Get initialized with
{}
, for instance:{firstName: "Aryan", lastName: "Sharma"}
Objects are “heavier” than primitives. They require additional resources to support the internal machinery.
Why Primitive is Unique
Immutability: Once a primitive value is created, it cannot be altered. For instance, when you create a string, you cannot change its individual characters.
let str = "Don";
str[0] = "S";
console.log(str); // Don ...No change
Memory Storage Efficiency: Primitives are stored directly in the stack memory where the variable is located.
let n = 123; // Stored directly in memory where 'n' is located
Objects in JavaScript
Objects are more complex structures in JavaScript.
Mutable: They are mutable.
Reference Type: Objects are reference types, stored as references.
Versatile: Can store any datatype.
Object Wrappers: Look Up
String for string primitives.
Number for numeric values.
Boolean for boolean values.
Symbol for symbol primitives.
BigInt for bigint numbers.
String Methods
Though primitives, can utilize various object methods.
For instance:
let name = "Programmer";
console.log(name.toUpperCase()); // PROGRAMMER
Numbers Methods
Numbers also have methods that can be used similarly. Consider the toFixed()
method.
let pi = 3.14159;
console.log(pi.toFixed(2)); // Output: "3.14"
Boolean Methods
Booleans can be wrapped with the Boolean
object to utilize additional methods.
For example:
let flag = false;
console.log(flag.toString());
Symbol and its Methods
A unique primitive type in JavaScript, can also use methods from the Symbol
object:
let sym = Symbol("description");
console.log(sym.toString());