Tuesday, January 7, 2020

Understanding Javascript - Part2

Some more concepts to explore... lets begin ....

  •  Copying Objects and variables in JavaScript

1. In Javascript, the objects and arrays when copied are done with reference. To show with an example.

Eg1:

let object1 = {

name : 'John'
};
const secondObj = object1 // copying the object here.
secondObj.name = 'Mary';
console.log("Name", object1.name) // What do u think will be printed here ..... ??
Answer : "Mary"

The answer above is Mary because the object was copied with reference i.e the pointer is referenced not its value. To resolve the issue obove we would have to do something like this:

const secondObj = {
...object1 // spread
}
secondObj.name = 'Mary'
console.log(object1.name) // this will print John

2. Variables are copied by Value, i.e the way we understand direct.

  • Garbage Collection in JavaScript
Every language has its way of gc (garbage collection) i.e to clean the memory when variables are no more used.

An object is considered garbage when there are zero references pointing to it.

Dont worry, Javascript does this automatically for us. We only need to make sure in our code we do not have any objects/Variables globally defined which might not be garbage collected at all.

  • Error handling in JavaScript
There are many ways error handling could be done. As a developer we should be handling them wisely.
    • Try Catch Block
    • Callback functions/Promises
    • Logging error
    • Displaying to user if necessary. 
Basically there are 2 types of errors operational errors (system errors) and programmatic errors (errors results from bug in the code).

Let me know if you have some more inputs to these, it would definitely help me improve upon my knowledge :).

No comments:

Post a Comment