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

Wednesday, December 18, 2019

Javascript scopes (THIS)

The "This" in JavaScript is pretty confusing and i guess requires a whole POST to describe different scenarios to understand it better.


  • So, by default "This" points to the global scope or window scope in a function.

function a() {
console.log(this) // this is global scope, or window scope
}

  • In case we make of 'use strict' mode then "This" points to undefined.

Basically, "This" is set based on from where the function is called. Eg.

var name = 'Elsa';
function callName() {
console.log("name", this.name)
}
var obj = new callName(); // This would print 'undefined', this would point to window object this.window.name == 'Elsa'

  • Another point to be noted, if we have a method inside an object then "This" points to the object.

Eg below:

var obj1 = {
  name: 'Prem',
  func: function() {
   console.log(this.name) // this refers to obj1
  }
}

obj1.func() // this would print 'Prem'


  • We can change the scope of this using certain functions like this, using the .call method

var obj1 = { name: 'Prem', func: function() { console.log(this.name) // this refers to obj1 } } obj1.func() // this would print 'Prem' var obj2 = {name: 'Ratan'} obj1.func.call(obj2); // this would print 'Ratan'

Always make sure to identify the difference between a global variable and local variable even
though the variable name is same.
One last example:

function movie() { var name = "Prem"; // this is a local variable of movie func this.maker = "Ratan"; // this points to global scope here console.log(this.name + " " + maker); // output: undefined Payo } var name = "Dhan"; // global variable var maker = "Payo"; //global variable obj = new movie(); // This will create an object of function movie() console.log('maker', obj.maker); // this will print Ratan

In the above example this.name and name are 2 different variables,
similarly this.maker and maker.

Saturday, November 30, 2019

My Understang of Javascript - Part1 (Basics)


When i started with Javascript, i would not understand as to why is it considered so special as compared to other languages and what is it that makes it different.

Certain things i found interesting, u might as well :)

First thing to Note... Everything in Javascript is an Object, or atleast derived from an object.

Primitives in Javascript are String, Number, Boolean, Null and undefined.

1. Functions

Functions in javascript are different because they can take any form. What i mean by this is functions are objects i.e they are called function objects. Other differences are functions can be passed as a parameter, it can be returned just like any other variables, that is reason why they are called the first class citizens. (Higher order functions)


2. Hoisting

What is hoisting? As the name suggest hoisting means raising something (like hoisting a flag [:P]).
Ok, enough of ENGLISH meanings , lets get back to Javascript.

In JavaScript all the variables are hoisted to top, i.e all the declarations only are hoisted not its assignment. below with example.

Program 1:
console.log(a);
var a= 10;

In Program 1 the value of `a` would be undefined, it will not throw an error as compared to other languages, reason being "Hoisting".

After hoisting the Program 1 would look something like this:
var a;
console.log(a);
a=10;

So, the declarations of a is taken to the top and not its assignment.
All the variables declared are by default set the value of undefined.

You can try the above example or various other examples to make this concept clear.

3. Scopes

Scope means up to where a particular variable would be available in a program/script.


Scopes belong to global scope, function scope. Lets understand each one and how they work.

a. Global scope: Is the one that is not inside any function or in short it starts with the first line of the code.
b. Function scope: This scope starts with the function and ends with the last ending brace. Variables inside the function are not accessible outside are called the local variables.

There is something more to this... The Closures ... lets unsderstand this with an example.

function a() {
   var alocal = 10;
   function b() {
     // variable alocal is accessible here
    console.log(alocal) // will print 10.
   }
}

Inner function has access to its outer function, thats why it can access the variable alocal.

4. "This" Scope

By default this points to the outermost global scope i.e window.

The scope of "this" changes depending on the way it is called.

In a function the "this" points to the global scope

function a() {
//this = global scope
}

Similarly function inside a function also points to a global scope.
function b() {
 function c() {
    // this still points to the global scope
 }
}

Only incase of objects its different.
var objLocal = {
loc : 1,
func: function() {
console.log("this", this); // this points to object scope and not global
}
}
We could change the scopes using .call() , .apply() methods

This is just the start, many more things to explore.. will post more in the coming blogs.

Thats all in this blog FOLKS!!


Tuesday, December 16, 2014

Things to know to start with web programming


I Remember when i was a fresher and learning PHP had to go through many sites to come to a conclusion.!! Let me put all that search in just one GO ........

PHP is a very simple language...and learning is even more easier.
Some basic understandings and you are up and Running to build websites [:)].

To start with... lets go through some basic and important things you need to know before you start PHP.
We need to know some of the basic concepts like


  • How does a end - to - end http request/response work. Having said HTTP is stateless i.e it does not remember its previous state (GAJINI).


Let me write things in step format to understand better.

1. User enters a sitename eg: gmail.com and presses enter.
2. The request goes to the server.
3. The server receives the request and sends the response. The response also contains the 'status code' , 'content-type' for the browser along with the unique identifier which will be sent each time some fuether correspondence with the same site is made. This identifier is used to identify whom to send the response to.
4. The response is then displayed to the user.
5. Next time user sends a request it will also include the same identifier sent before so the server knows that this is same user who has sent request before. Based on this identifier further processing is done.

Now, with the above steps comes into picture the "Cookies" , "Sessions".

-  Cookies : These are stored at client side, which means that they are stored at a particular location on the computer the user uses. So these can be modified any time by the user. That is the reason why it is not safe to store secure information in cookies.

- Sessions : These are stored at server end, i.e they will be stored on server somewhere where the user will not have direct access to. So are more secure as compared to cookies.

So the basic question... will the sessions work if cookies are disabled on browser??
Answer is no and yes. No because the sessions will not work as they work with post since it will not receive the unique identifier to identify the user. Yes because to have this working we could send the identifier as a query string in the browser.



  • Whether to use POST/GET when sending a request.
- POST request : This will be used when you have to send some secure information which you do not want anybody to alter with. This anybody here is a hacker or some person who acts as an intermediary and steals information.
eg: When sending username and password send it using POST since the information should not be stolen and altered in between.
POST is also used when you want to send large amount of information in the request.

- GET request : This will be used sending things that do not require any security. 
eg: Sending page nos could be done using GET.
Mostly used when the amount of information sent is small. i.e you cannot be sending large data in the query string.

  • Whether to use global variables
I would rather say no because global variables are like prostitutes and anybody could alter with in the code. So instead go with sessions.

  • Buffering
PHP supports buffering. Advantage is it will help reduce the page load time. i.e we store the whole HTML in a variable and display all at once. instead of having load things slowly as parsing proceeds.


And last but not the least.....

PHP is an interpreted language... which means that when running it starts from the top of the page and proceeds line by line till the end of the page. And if any fatal error is encountered then execution stops there itself.


Do let me know if have missed out or you find some mistake in there....