Hello I am an Object π
Questions π€
- What is
this
? hows that work? - Why do we bind
this
keyword in react application?
we useclass-based components
we need to bind this keyword to the class. Because the method we are passing to the Event Handler is invoked in the global environment where this keyword refers to the window object - How does object work in javascript?
- How to make an object property undeletable?
- const vs Object.freeze()
- What are the different ways to clone an object?
- Shortcut method to declare an object
- What are the different ways to access object properties
- Object.is() vs ===
- What are the different ways to check the existence of object property
- How do you loop over Objects
- Object to primitive conversion
this
π¨
What the hell is In a simple word this
is the object that is executing in the current context.
Not understanding it right! let me tell you in this way.
Lets say this
in module 2 is quite interesting it contains quite a lot of crazy pieces of stuff. In a statement this is referring to the module 2 which means module 2 is my current context. Now I hope you got some hint π
Remember
The value of this
will differ in how a function is invoked. So it's hard to judge the value of this
There are 5 thumb rule for this
which decide the value of this
object
- Simple Function Call
- Implicit Binding
new
Binding- Explicit Binding
- Arrow function
1. Simple Function Call
If this is part of regular / Simple function then this
will refer to window
object in browser and global
object in the node
2. Implicit Binding
If the function is part of an object (We call it as a method) this
will refer to the same function
We can also extend the object by adding the new method but still this
will refer to the same object
Let's see one more example
If you see the above example I got undefined why is that? π’
Answer is we have forEach
loop inside the play()
and only play()
method is member of song
object where as forEach
is member of global/window object
To solve that what we can do is, Since forEach accept callback method and thisArg we can pass the this
object to solve our problem
new
binding / Constructor function
3. If we create an object for a constructor function using a new
keyword this will refer to the construction function instead of the global/window object.
This is because when we use the new
keyword it will create an object {}
and bind the function property that we defined
In the above example, it created an empty object i.e {}
and bind organization
into that
4. Explicit Binding
We can explicitly tell the JS engine to set this to point to a certain value using call
, apply
or bind
.
call
and apply
can be used to invoke a function with a specific value for this
Both call
and apply
accomplish the same purpose. The first arg is the object which it wants to refer in out case marvel
bind
is used to create a new function thatβs permanently bound to this value.
Strict mode use strict
and this
this
work differently in strict mode use strict
5. Arrow function / Lexical environment
Before arrow functions, every new function defined its own this value based on how the function was called but Arrow functions do not have their own this
value
With an arrow functions, this keeps the same value as its parent scope i.e and Object space
Object
Everything in javascript is Objects
and Primitive
.
We have seen lots of example with respect to object and there are multiple ways to create objects
Shorthand technique to declare an Object
If we want to create an object with the same key then we can declare something like this
Technique to deep cloning an object π§π»βπ€βπ§π»
Cloning an object without disturbing the original one is a bit crazy in javascript
If you see above sample code, if I change cloned object even the original object gets affected this is because of both object is referring to the same address in the memory, even if we loop through and put property into the item will not solve our problem
Object Behavior
A loop that copies each property to a new object would only copy enumerable properties on the object. Enumerable properties are properties that will show up in
for
loops andObject.keys
.The copied object has a new
Object.prototype
method, which is not what you want when you copy an object.If your object has a property that is an object, your copied object will refer to the original instead of creating an actual copy. This means that if you change that nested object in the copied object, the original gets changed as well.
Any property descriptors are not copied. If you set things like
configurable
orwritable
tofalse
, the property descriptors in the copied object will default totrue
.
to avoid that we have multiple solutions those are like below
πΈ Object.assign
new static method on the Object constructor: Object.assign. This new method allows us to easily copy values from one object to another.
Remember
only an object's enumerable properties will be copied over with Object.assign.
πΈ Using third party lib
Using Lodash
Clone And Clonedeep
Technique to check the existence of object property
πΈ hasOwnProperty()
in
operator
πΈ πΈ Comparing with undefined
Type of Object Properties
πΈ Data Properties
A very common most widely used way
πΈ Accessor Properties
These properties can be understood as getter and setter similar to other modern programming languages
If we try to set a name in an object in which we declared get than new value is can not set and vice versa
Conventional private property
πΈ Computed Properties
Computed Property Namesβ feature allows you to have an expression (a piece of code that results in a single value like a variable or function invocation) be computed as a property name on an object.
Computed Properties is very helpful when we want to generate a random key for an object
Object Property Descriptors
Every key in an object will have Property Attribute
that defines the characteristics of the value associated with the key. They can also be thought of as meta-data describing the key-value pair. In short, attributes are used to define and explain the state of object properties.
There are total 6 property attribute
πΈ [[Value]]
It stores the value retrieved by getting access to the property. This means that when we do object.x in the above example, we retrieve its [[Value]] attribute. Any dot-access or square-bracket access of a Data property will work in this way.
πΈ [[Get]]
It stores the reference to the function that we declare while making a getter property.
πΈ [[Set]]
It stores the reference to the function that we declare while making a setter property.
πΈ [[Writable]]
This is a boolean
value. It tells whether we can overwrite the value or not. If false, attempts to change the propertyβs value will not succeed.
πΈ [[Enumerable]]
This is also a boolean value. This attribute dictates whether the property is going to appear in for-in loops or not. If true, the for-in loop will be able to iterate on this property.
πΈ [[Configurable]]
This is a boolean too. when its false following things will take place
delete
property is not possible- Converting a Data Property to be an Accessor Property or vice-versa will fail
- It will also prevent further changing the values of the attributes. That is, the current values of enumerable, configurable, get, or set will become fixed.
- When the property is a Data Property, you can only set writable from true to false.
- Before writable becomes false, you can also change its [[Value]] attribute. However, once writable is false, and configurable is false too, the property becomes unwritable, undeletable, and unchangeable.
All six properties do not exist for each property type.
- For Data Properties, only
value
,writable
,enumerable
andconfigurable
exists. - For Accessor Properties, instead of value and writable, we have
get
andset
.
Why have we wrapped the attribute names in [[]] π€·π»
Double square brackets mark internal properties used by the ECMA specifications. These are properties that JS programmer cannot touch directly from within the code. To manipulate internal properties, weβd need to use methods provided to us by the language.
Working with Descriptors π
πΈ Object.getOwnPropertyDescriptors
This method returns either undefined or an object containing the descriptors
πΈ Object.defineProperty
Itβs a static method on Object that can define or modify a new property on a given object. It takes three arguments β the object, the property name, and descriptors. It returns the modified object.
Protecting an Object π
We may find a use case to avoid tempering our object and JS have the flexibility to do so with these following methods
πΈ Object.preventExtensions
The Object.preventExtensions method prevents new properties from ever being added to an object. It takes an object and makes it non-extensible
πΈ Object.seal
The seal
method seals an object which It prevents new properties from being added just like Object.preventExtensions
.
- It marks all existing properties as non-configurable
- Values of present properties can still be changed as long as they are writable.
- In short, it prevents adding and/or removing properties.
πΈ Object.freeze
provide maximum protection any object can have in JavaScript. Internally it seals the object using Object.Seal
- It also prevents modifying any existing properties at all.
- It also prevents the descriptors from being changed as the object is already sealed.
Create | Read | Update | Delete | |
---|---|---|---|---|
Object.freeze | β | β | β | β |
Object.seal | β | β | β | β |
Object.preventExtension | β | β | β | β |
info
const
makes the variable binding immutable but its value can still be modified.
Object.freeze()
ignores the value modification to an object but there is no restriction on the binding.
Other Object Methods
πΈ Object.Keys
The Object.keys static method returns an array with the property keys on an object. This method can be really useful in allowing to use a forβ¦of loop over an object
Note that in the array returned from Object.keys, the keys won't necessarily be in order.
πΈ Object.values
Object.values takes an object and returns an array with the values, in the same order that a forβ¦in loop would give us
πΈ Object.is
Object.is()
behaves almost same way as ===
Object.is(arg1, arg2) checks the arguments for equality the same way as the strict equality operator, but with the 2 differences.
- Firstly, NaN equals to another NaN value
Object.is()
makes the distinction between -0 and +0
πΈ Object.entries
Object.entries returns an array with arrays of key-value pairs
πΈ Object.isExtensible
Helps to check whether the object is non-extensible or not If it returns true, you can add more properties to the object.
?.
null Propagation Operator / Optional Chaining Ensuring any object or variable is contain any value or not is the primary focus area of any developer to get rid of application crashing. To rescue that 'null Propagation Operator' is a savior else we need to check each and every element explicitly
lodash
can also help to solve this problem, with less unwanted complexity
The optional chaining ?.
stops the evaluation and returns undefined if the part before ?.
is undefined or null.
We should use ?.
only where itβs ok that something doesnβt exist.
For example, if according to our coding logic movie and infinity war
object must be there, but the character(s) is optional, then marvel.movie.infinityWar?.character1 would be better.
So, if a user happens to be undefined due to a mistake, weβll know about it and fix it. Otherwise, coding errors can be silenced were not appropriate, and become more difficult to debug.
Tips π
Optional chaining also works with functions and square brackets.
obj?.[prop]
β returns obj[prop]
if obj exists, otherwise undefined
obj?.method()
β calls obj.method()
if obj exists, otherwise returns undefined
??
Null coalescing operator The null
coalescing operator returns its right-hand-side operand when its left-hand-side operand is null or undefined, and otherwise returns its left-hand-side operand.
Things to remember
- This is a recent addition to Javascript. Old browsers may need polyfills.
- nullish coalescing will not threat falsy values
||
to support ??
Operator The OR ||
operator can be used in the same way as ??
. We can replace ??
with ||
The important difference is that:
- || returns the first truthy value
- ?? returns the first defined value
typeOf
and instanceOf
These operators are used to check the in which family that instance belongs to
typeOf
πΈ typeOf
is a unary operator that returns a string indicating the type of the unevaluated operand.
Use typeOf
operator for built-in types (primitive and objects)
instanceOf
πΈ instanceOf
is a binary operator, accepting an object and a constructor. It returns a boolean indicating whether or not the object has the given constructor in its prototype chain.
Use instanceOf
for custom types and complex built-in types
Host Object and Native Object
Host Object
Host Objects are created by the environment and are environment-specific. The best-known environment would be a web-browser or could be any other platform.
The host objects created in the web-browser could be the window object or the document.
Typically a browser uses an API to create Host Objects to reflect the Document Object Model
or DOM
into JavaScript. (Web browser have different JavaScript Engines that do this) A host object is created automatically the moment the page renders in a browser.
Example Window
, Document
, History
, XMLHttpRequest
(part of Web API), http
, https
, url
, etc
Native Object
A Native Object is created by the developer using predefined classes of JavaScript. These objects will have fully defined specification rather than by the host environment by
Standard native objects are defined in this specification. Some native objects are built-in; others may be constructed during the execution of an ECMAScript program.
Example Object
(constructor), function
, Date
, Math
, parseInt
, eval
, string methods
, array methods
, etc