Monday, August 10, 2020

why use spread operator or assign or freeze object


Copying using spread operator or assign would be mainly useful when using content from constant files, and you want to make sure none of the content is overwritten during the business logic.

1. One use would be to make a copy of an array.

const x= [1,2,3,4]

if we do,
const y = x; // this will only give another reference i.e x[1] = 6 then also y[1] would print 6.

So to copy

2. Combine 2 arrays or merging two arrays become much easier with the spread operator.

eg:
const a = {1: 'hello'}
const b = {2: 'there'}

const c = {...a, ...b}

output: c {1: 'hello', 2:'there'}

With ES5 we would have to use something like assign function to update an existing array.

So far so good, we know when to use assign or spread operator.

Suppose, we have an object which is not supposed to change throughout then we can go for Object.freeze();

This freeze function will ensure that the values inside it are never changed, and any attempt to do so will throw an error.

Thats all for this post :)


Wednesday, June 3, 2020

Javascript is interpreted or compiled language and why - Interview question

In one of the interviews i was asked whether JavaScript is interpreted or compiled language... and as per my knowledge i said with confidence it is "Interpreted"... And yes it is correct.

Then what is done in hoisting in JavaScript... it is not compiling?? (2nd question from interviewer).

Yes, there is a difference here. Hoisting does not mean compiling.

First of all, lets understand what is done in interpreted languages like java script.

Interpreted means it runs the code "line by line" and when error found it just stops at that particular line. i.e the whole code is read and understood only when running it and not beforehand.

Compiling is to convert a language into byte code for the machine to be able to read and understand.
So before running a code, there is package generated when compiling and when successful only then running of the code happens unlike JavaScript.

Finally coming to Hoisting.. it has been done by JavaScript developers in the same language where it only moves the declarations on top, not the assignments. It does not convert the code into byte-code or anything for that matter.

Hopefully my understanding are setting your understanding as well right :)

Please correct me.. if you find something wrong. (Will definitely add something to my knowledge)

Thanks for reading.

Monday, May 11, 2020

arrow functions v/s normal functions


Arrow functions were introduced with ES6, also called the FAT Arrow functions.

Lets point out some differences between these 2 types of functions.


1. Syntax wise arrow functions look pretty short and sweet

 so one would think of using them every single time instead of a normal function. But, this cannot be true every time since the scope of arrow functions works differently.


Arrow Function
a() => {}

Normal function
function a() {
}


2. Scope of this in arrow functions.


Arrow functions take the 'this' using lexical scoping from its parents, whereas normal function have the current function used as 'this'.
Eg:


  • Function inside a function case.

function normal() { this.localVar = 10; normalinner = function() { console.log("printing localVar", this.localVar) // 10, as 'this' points to normalinner function. But it is able to access variables from parent function (closure) } arrowinner = () => { console.log("printing localvar inside arrow", this.localVar) // 10, as 'this' points to parent function norma } normalinner(); arrowinner(); }


  • Function inside a object case 

let object = {
  localObjVar : 10;
  localObjFn : function() {
    console.log("localObjVar", this.localObjVar); // 10, 'this' points to the object here.
  }
 localObjArrFn : () => {
  console.log("Arrow fn localObjArrFn ", this.localObjVar ) // undefined, as 'this' points to the global scope here.
 }
}

3. Arrow functions are only callable and not constructible.


It only means that Arrow functions cannot be called with new key word, normal functions can be called with new keyword.

let a = new a() // allowed for normal functions, whereas if a is an arrow function then it would throw an error "a is not a constructor".

Thanks for reading!

Monday, March 23, 2020

Understand the let and const internally

In my previous post, i had mentioned how the let and const works in Javascript, Now lets dive a bit dipper to understand why things work that way (Memory).

According to what i read and understood, let me put it in my own words.

It is always advisable to use const or else let if variable value is to be changed.

In memory there is something called the stack and heap. All the primitive types are stored on stack and non-primitives are stored on heap.

Primitive types : String, number, boolean, null, undefined.
Non-primitive types: Object, Arrays, functions

For example:

let a=10;

'a' will be stored on the stack, since it is a primitive. Internally in memory 'a' refers to a address which is storing 10. i.e something like


Identifier
Stack
a
6sdfjk7skd
10

So now if we have something like:
let myVar = a;

in the above case we know value of myVar is also to 10 i.e myVar is also pointing to same memory address as the one 'a' is pointing to.

But, if we next set a=20, then will the value of myVar also change? ... No it will not because internally a new memory address is assigned to 'a', which has a value of 20.

Identifier
Stack
a
jfhsfjdsgkd
20
myVar
6sdfjk7skd
10


Lets understand const incase of primitives, why it throws an error when we do something like:

const a=5;
a=10 // gives an error as we cannot reassign const.

What actually happens internally is the following:
the above 2 lines are added to memory like so, in the second row it gives an error when reassigning the memory address to the new location.
Identifier
Stack
a
jfhsfjdsgkd
10
6sdfjk7skd
20


When using non-primitive types like Array, heap comes into picture
example: 

const myArr = []; // variable stored on stack, but its value is stored on heap.

Identifier
Stack
myArr
jfhsfjdsgkd
7hhhhhhh


Heap
7hhhhhhh
[]


myArr.push(10);
After adding the value of 10 , it is updated on Heap address like so, Stack remains the same.
Heap
7hhhhhhh
[10]


This is the reason why we could add or update even after having const for myArr.

Please let me know your comments , suggestions , corrections if any.

Monday, February 3, 2020

Main differences between Let and Var, and const.

The main uses of Let and Var is to declare a variable, based on the usage you would use either "Let" OR "Var ".

Here are some of the differences based on which it becomes easier to identify which one to use.

1.  Var was present right from before where as let is present from es6 (ES2015)
Ok, this difference does not make much of a difference as far as using it is considered [:P]


2.  Let is block scoped and var is function scope.
This difference would make much effect. Lets dive a bit dipper to understand.

Let is block scoped, which means it is not available outside a pair of parenthesis {}.
eg: 

function a() {
  {
     let localLetVar = 'local let var';
     var localVar = 'local variable'
  }
   console.log(localLetVar) // this will print undefined as it is not available outside the parenthesis.
   console.log(localVar) // this will print its value
}
a();

From the above example it should be clear, that "let" is block scoped, whereas "var " is function scoped, which means it is available inside until function ends.

3. For variables declared with "Var", Javascript hoisting happens, whereas variables declared with  'let' does not support javascript hoisting.
We definitely need to understand this, to avoid any surprises later in the code.
Eg:

console.log(a); // this will print undefined as hoisting happens i.e declaration happens for 'a'
var a=1;

console.log(b); // this will print error "b is not defined".
let b=2;


Lets also understand what is it with "const".

We all know "const" as the name suggests is like final in oop, but in javascript there is also something more to it. Lets understand with an example.

In cases of using objects/arrays in javascript.

const a=[1,2];
a.push(3) // allowed

object could be modified, i.e adding or removing values but not reassign.
you cannot do something like again after assigning.

a = [1,2,3]; // this is not allowed

In case of Let/var it allows reassigning as well.

Hopefully the above differences will help you  make a good decision. :)

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 :).