Javascript Objects

There are a total of eight data types in Javascript. Seven of them are ‘primitive’ and other is ‘object’. Primitive is something that contains a single thing (string
or number
or others). Objects are collection of key value pair
.
Creating an object
// Contructor syntaxconst objConstructor = new Object();// Literal syntaxconst objLiteral = {};
There are two ways of creating an object in javascript. One is object constructor syntax and other is object literal syntax. The common way of creating an object is through literal syntax.
Properties
Adding properties
// Immedaitely adding propertiesconst userObject = { // creating an objectname: 'Aniket', // added property 'name' with value 'aniket'age: 20, // property 'age' with value 20"like orange": true // multiword as property};// Adding property lateruserObject.like = 'Apple';// Another multiword as key// Multiword keys needs to be set/accessed using square bracket syntaxuserObject['like apple'] = true;
Deleting property
delete userObject.like;delete userObject['like apple'];
Accessing Properties
userObject.name; // AniketuserObject.age; // 20userObject.like orange // error occured// multiword key can be accessed using square bracket syntaxuserObject['like orange']; // true
Computed properties
The properties can be some computed values and can be used inside literal like so:
const language = prompt('which language you like ?', 'javascript');const likesObject = {[language]: 'you are the best'// language is computed from value of variable langauge};alert(likesObject.javascript);// if langauge == 'javascript' then alert 'you are the best' :p
Properties shorthand
const id = 1234;const userObject = {id, // same as id: id// it saved us of writing extra ;)};
Property limitations
The property name can be a string or symbol. Other types are converted to a string. For example, we try to make the property as 2 (number) it gets converted to “2”.
const object = {2: 'two',};alert(object['2']); // twoalert(object[2]); // two (excat same property)
Reserved keyword of language can be used as properties, for example, let, for, the return can be used as property names. Objects have a special property __proto__
which can is reserved and should not be directly modified.
// Reserved words can be usedconst object = {let: 'let',for: 'for',return: 'return',};alert(object.let);alert(object.for);alert(object.return);// __proto__ is special reserved property on a object// it is a object datatype, should not be modified directly
Property existence
Accessing a non-existing property on object results in undefined
but it is to note that the value of some property can be undefined
also.
const userObject = {propertyExist: undefined,};userObject.nonExistingProperty; // undefineduserObject.propertyExist; // undefined
So is there a way to know if property physically exists on the object? Yes, in
the keyword is used in such scenarios.
const userObject = {propertyExist: undefined, // intentionaly put as undefined};userObject.nonExistingProperty; // undefined'nonExistingProperty' in userObject; // falseuserObject.propertyExist; // undefined'propertyExist' in userObject; // true
Good practice: the value of the property should never be undefined
instead, use null
.
Ordered keys
Keys on the object are sorted in a special fashion. Integer keys are sorted and others appear in order of creation.
// integer keysconst rollName = {'40': 'john''20': 'aniket','21': 'albert',};for(let key in rollName){console.log(key, rollName[key]); // 20 aniket 21 albert 40 john}// string keyconst nameRoll = {john: 40,aniket: 20,albert: 21};for(let key in nameRoll){console.log(key, nameRoll[key]); // john 40 aniket 20 albert 21}
By Reference
Objects are reference type. In the following example imagine userObject
as a bucket that refernces/points to a store/section in memorary which holds the object itself.
;
const userObject = {};// variable userObject ----> store/section of memorary which holds // {}
Copying an object
An object is copied by reference, not value or duplicated. This can be seen in the following example where user reference is copied to the admin variable bucket. And when name property of admin is modified the property value of name on user also changes, this indicates that both refer to the same location in memory.
const user = {name: 'Aniket'};const admin = user;admin.name = 'John';user.name; // 'John' ? refer to same object thus got modifiedadmin.name; // 'John'// alsoalert(admin === user); // true : same reference
🤔 so reassigning doesn’t copy object value but its reference. But what if I need to duplicate or clone the object into a new variable.
const user = {name: 'Aniket',age: 20,};/// solution 1// adding keys one by one in a for...in loopconst admin = {};for(let key in user){admin.key = user.key;}// solution 2const admin = Object.assign({}, user);// solution 3const admin = { ...user };
Solution 1: It is adding property one by one in a loop.
Solution 2: This is something important Object.assign(destObject, [srcObj1, srcObj2, ...])
. The Object.assign takes a destObject
object onto which properties of srcObj1
, srcObj2
and many others are copied.
Solution 3: { ...obj }
the ...obj
is spread syntax to spread properties of obj
, it is spread on { }
object.
The End
The Object
are very important in javascript, it penetrates every aspect of language. In future, we will look some more javascript stuff stay tuned. 😊