What is an Object an JavaScript ?
————————————————
Everything in Javascript is basically an Object.
Javascript has two different data types
- Primitive
- Non Primitive
There are seven different primitive data types in Javascript
- string
- number
- boolean
- null
- undefined
- symbol
- Bigint
Non primitive Data type is an Object which contains multiple values in the form of
Key : Value pair
Primitive types are immutable.
If we declare a variable with var or let keyword e.g.
var x = 10;
var y = 20;
We can reassign values
x = 15;
y = 20;
But if we declare and assign values using const keywords, we cant re-assign values.
const a = 30;
a = 40 // not allowed
But Objects are mutable. Even if we declare an object as constant, we can re-assign different values to its properties.
e.g.
const testObj = {
name : “John”,
address : “USA
}
We can change the value of name
testObj.name = “David”
Objects don’t hold the actual values, but the reference instead. Primitive types hold the actual values there by immutable.
So the question is how to protect the values of the Object properties.
One of the solutions is
using “Object.freeze()” along with the “use strict” directive.
Object.freeze(testObj);
Now if i try to change the property value.
testObj.name = “Jennifer”
console.log(testObj.name);
—————————————
O/p
David