This content originally appeared on DEV Community and was authored by Abhinav Kale
We know that javaScript sometimes behaves weird as compare to other programming languages, but initially it was design only to make web pages.
But now in today's world, we can do so many things using javaScript with help of other libraries/framework like react, angular.
This weird behaviour is not a fault of javaScript, this is how the language was design in the initial phase. So we should understand why this behaviour happens, so we can take primitive actions based on it.(If we are intending that this should not happen)
So here, we make one object calling its name weirdObject which has property obj_id
and obj_name
which is further divided into an object which has property obj_title
and type
.
If we run our code with node we get the output as the object considering obj_id
and obj_name
.
Now, if we want to change the obj_id
of the object we can do that in javaScript inspite of using const keyword.(It is allowed to change inside property of javaScript whether we use const or not)
To change this behaviour, we can use Object.freeze() method which freezes an object.
Here the value of obj_id
not changed. A frozen object can no longer be changed; freezing an object prevents new properties from being added to it, existing properties from being removed, prevents changing the enumerability, configurability, and writability of existing properties, and also prevents the values of existing properties from being changed.
But, what if we want to change value of the obj_title
from "My Object" to "This Object" which is present inside obj_name
object of weirdObject after using Object.freeze()
method.
Yes, we can do that..!! This is called Shallow freeze which only applies to the immediate properties of the object itself and will prevent future property addition, removal or value re-assignment operations only on object. If the value of those properties are objects themselves, those objects are not frozen and may be the target of property addition, removal or value re-assignment operations.
To make object immutable, we will have to add explicit function which will check is wheather the object has another object present inside it.
Hope this odd behaviour of javaScript information helps you.
Thanks for reading and happy coding!
This content originally appeared on DEV Community and was authored by Abhinav Kale
Abhinav Kale | Sciencx (2022-01-10T15:53:26+00:00) Weird behavior of javaScript you should know!!. Retrieved from https://www.scien.cx/2022/01/10/weird-behavior-of-javascript-you-should-know/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.