Table of contents
No headings in the article.
Objects are the heart of JavaScript. Objects are used to store data as a key value pair where keys are unique for every value. Objects are the non-primitive data types that can store multiple and complex values which can not be done by the primitive data types (String, Number, BigInt, Boolean, etc). Let's dive deep into objects.
let Student = {Name: 'Devi'}
Here Student is a object that has 'Name' as key or property and 'Devi' as value. We can access the value of keys in the following ways.
console.log(Student.Name) // output : Devi
console.log(Student['Name']) // output : Devi
key of the object should always be a string value, if we do not define it to be string, JavaScript itself convert it to the string.
let Class = {1:'First'}
console.log(Class) // output : {'1':'First'}
If we try to use a variable as a key for JavaScript object, it does not give the desired result.
let key = 'Name'
let Student = {key: 'Devi'}
console.log(Student) // output : { key: 'Devi' }
However we can get the desired result with the help of Square braces.
let key = 'Name'
let Student = {}
Student[key] = 'Devi'
console.log(Student) // output : { Name: 'Devi' }
What if we use objects as a key?
let Student = {}
let Name = {key: 'Name'}
let RollNo = {key: 'RollNo'}
Student[Name] = 'Devi'
Student[RollNo] = 123
console.log(Student) // output : { '[object Object]': 123 }
When we pass a non-string value as a key, JavaScript convert it to a string and when we convert an object to string [object object] is returned.
let Name = {key: 'Name'}
console.log(toString.call(Name)) // output : [object Object]
let RollNo = {key: 'RollNo'}
console.log(toString.call(RollNo)) // output : [object Object]
Hence Student object will have only one key 'object Object' and it will store 'Devi' first and later the value will get overwrite by 123.
In JavaScript arrays are of object type.
let Names = ['Devi', 'Jay', 'Sam']
console.log(typeof(Names)) // output : object
Number, String, Boolean when defined with new keyword are objects. Dates, Math, Regular expression, functions all are objects. So It is safe to say that almost everything in JavaScript is object.